Guide to Java 8 groupingBy Collector | Baeldung
2.2. Simple Grouping by a Single Column
Let's start with the simplest groupingBy method, which only takes a classification function as its parameter. A classification function is applied to each element of the stream. The value that is returned by the function is used as a key to the map that we get from the groupingBy collector.
To group the blog posts in the blog post list by their type:
1 2 | Map<BlogPostType, List<BlogPost>> postsPerType = posts.stream() .collect(groupingBy(BlogPost::getType)); |
2.3. Grouping by with a Complex Map Key Type
The classification function is not limited to returning only a scalar or String value. The key of the resulting map could be any object as long as we make sure that we implement the necessary equals and hashcode methods.
To group by the blog posts in the list by the type and author combined in a Tuple instance:
1 2 | Map<Tuple, List<BlogPost>> postsPerTypeAndAuthor = posts.stream() .collect(groupingBy(post -> new Tuple(post.getType(), post.getAuthor()))); |
Read full article from Guide to Java 8 groupingBy Collector | Baeldung
No comments:
Post a Comment