使用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));
本文介绍如何使用Guava和JDK 1.8将集合转换为Map,包括处理重复键的方法,并提供具体示例。

被折叠的 条评论
为什么被折叠?



