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;
}
}
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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With