Java 8 : How to do grouping data using Stream API ?

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;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s