List<User> users = new ArrayList<>();
users.add(new User(4L,"liuliu"));
users.add(new User(1L,"zhangsan"));
users.add(new User(3L,"wangwu"));
users.add(new User(2L,"lisi"));
Map map4 = users.stream().collect(Collectors.groupingBy(User::getUserId));
Map map1 = users.stream().collect(Collectors.toMap(User::getUserId,
Function.identity(), (x, y) -> x));
Map map2 = users.stream().collect(Collectors.toMap(User::getUserId,
User::getUsername, (x, y) -> x));
Map map3 = users.stream().sorted(Comparator.comparingLong(User::getUserId)).collect(Collectors.groupingBy(User::getUserId));
System.out.println(map1);
System.out.println(map2);
System.out.println(map3);
System.out.println(map4);
class User{
private Long userId;
private String username;
public long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User(Long userId, String username) {
this.userId = userId;
this.username = username;
}
public User() {
}
}