When we have a list of objects and we want to group them by an attribute is easier now. In this example I have a list of restaurants and I want group them by categories such as vegetarian, French, Italian. See how easy it is.
List<Restaurant> all = restaurantService.findAll(); Map<Category, List<Restaurant>> map = all.stream().collect(groupingBy(Restaurant::getCategory));
public class Restaurant { private Category category; private List<Dish> dish; private String name; public List<Dish> getDish() { return dish; } public void setDish(List<Dish> dish) { this.dish = dish; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
public class Category { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }