I have a list of restaurant objects with attributes like city, type, rating, and I want to print the list with the highest rating for this combination (city, type). Since I created this example to use a java thread, answer how this can be done with threads:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Optional;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.groupingBy;
import static java.util.Comparator.comparingLong;
class Restaurant {
public String city;
public String type;
public Long rating;
public Restaurant(String city, String type, Long rating) {
this.city = city;
this.type = type;
this.rating = rating;
}
public String getCity() { return city; }
public String getType() { return type; }
public Long getRating() { return rating; }
}
public class HelloWorld
{
public static void main(String[] args)
{
List<Restaurant> mylist = new ArrayList<Restaurant>();
mylist.add(new Restaurant("City1", "Tier1", 1L));
mylist.add(new Restaurant("City1", "Tier1", 2L));
mylist.add(new Restaurant("City1", "Tier2", 1L));
mylist.add(new Restaurant("City2", "Tier1", 1L));
mylist.add(new Restaurant("City2", "Tier1", 3L));
mylist.add(new Restaurant("City2", "Tier3", 1L));
Map<String, Map<String, Optional<Restaurant>>> mymap =
mylist.stream().collect(groupingBy(Restaurant::getCity, groupingBy(Restaurant::getType, maxBy(comparingLong(Restaurant::getRating)))));
}
}
source
share