List转换Map的三种方式

 

1、for循环

  。。。

2、使用guava

 Map<Long, User> maps = Maps.uniqueIndex(userList, new Function<User, Long>() {
            @Override
            public Long apply(User user) {
                return user.getId();
            }
   });

3、使用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));

 

posted @ 2020-10-13 17:06  随心的风  阅读(1643)  评论(0编辑  收藏  举报