If you need to group list elements by some property of an element, Collectors.groupingBy()
methods could help.
Here is an example:
record Comment(Author author, String text, CommentType commentType) { }
record Author(String name) {}
enum CommentType {
GREETING, QUESTION, OTHER
}
Now, we have a list of comments:
List<Comment> comments = ...;
And we want to group comments by author, i.e., convert this list into Map<Author, List<Comment>>
. Here is how we can do this:
public Map<Author, List<Comment>> groupByAuthor(List<Comment> comments) {
return comments.stream().collect(Collectors.groupingBy(Comment::author));
}
And if we want to go further and group comments by author first, and then by comment type, then we can do it like this:
public Map<Author, Map<CommentType, List<Comment>>> groupByAuthorAndType(List<Comment> comments) {
return comments.stream()
.collect(Collectors.groupingBy(
Comment::author, Collectors.groupingBy(Comment::commentType)
));
}
There are many more use cases where the three Collectors.groupingBy()
methods could help. Take a look at Javadocs for more details.
Dream your code, code your dream.
Top comments (0)