DEV Community

Cover image for [Tiny] How to Group List Elements in Java
Petr Filaretov
Petr Filaretov

Posted on

2

[Tiny] How to Group List Elements in Java

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay