3

I want to group list of users by id() using Java Streams.

For example, I have List: new User(1L, "First"), new User(2L, "Second").

How can I group this list to get Map<Long, User>?

1L -> new User(1L, "First"),
2L -> new User(2L, "Second")

User.java

public final class User {
    final Long id;
    final String name;

    public User(final Long id, final String name) {
        this.id = id;
        this.name = name;
    }

    public Long id() {
        return this.id;
    }

    public String name() {
        return this.name;
    }
}
Roman Cherepanov
  • 1,560
  • 2
  • 23
  • 43

1 Answers1

2

If each ID is mapped to a single User, use Collectors.toMap:

Map<Long,User> users = list.stream().collect(Collectors.toMap(User::id,Function.identity()));
Eran
  • 374,785
  • 51
  • 663
  • 734