我想使用Java Streams按id()
分组用户列表。
例如,我有List: new User(1L, "First"), new User(2L, "Second")
。
如何将此列表分组以获取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;
}
}
答案 0 :(得分:2)
如果每个ID都映射到一个User
,请使用Collectors.toMap
:
Map<Long,User> users = list.stream().collect(Collectors.toMap(User::id,Function.identity()));