[Tiny] How to Group List Elements in Java

Petr Filaretov - May 11 '23 - - Dev Community

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
}
Enter fullscreen mode Exit fullscreen mode

Now, we have a list of comments:

List<Comment> comments = ...;
Enter fullscreen mode Exit fullscreen mode

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));
}
Enter fullscreen mode Exit fullscreen mode

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)
            ));
}
Enter fullscreen mode Exit fullscreen mode

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player