使用guava
Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
@Override
public Long apply(User user) {
return user.getId();
}
});
使用JDK1.8
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId,Function.identity()));
JDK 1.8。转换成map
的时候,可能出现key
一样的情况,如果不指定一个覆盖规则,上面的代码是会报错的。转成map
的时候,最好使用下面的方式:
Map<Long, User> maps = userList.stream().collect(Collectors.toMap(User::getId, Function.identity(), (key1, key2) -> key2));
map
的值是对象的某个属性,用下面的方式:
Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));