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));

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM