public static class User{
private Long id;
private String userName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
public static void main(String[] args) throws IOException {
List<User> users = new ArrayList<>();
User user = new User();
user.setId(1L);
user.setUserName(null);
users.add(user);
Map<Long, String> collect1 = users.stream().collect(Collectors.toMap(User::getId, User::getUserName));
}
应改为
Map<Long, String> collect2 = users.stream().collect(HashMap::new, (m, v) -> m.put(v.getId(), v.getUserName()), HashMap::putAll);