Java8中list轉map方法總結


list轉map在Java8中stream的應用
1.利用Collectors.toMap方法進行轉換

public Map<Long, String> getIdNameMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}

其中第一個參數就是可以,第二個參數就是value的值。
2.收集對象實體本身
在開發過程中我們也需要有時候對自己的list中的實體按照其中的一個字段進行分組(比如 id ->List),這時候要設置map的value值是實體本身。

public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}

account -> account是一個返回本身的lambda表達式,其實還可以使用Function接口中的一個默認方法 Function.identity(),這個方法返回自身對象,更加簡潔
重復key的情況。
在list轉為map時,作為key的值有可能重復,這時候流的處理會拋出個異常:Java.lang.IllegalStateException:Duplicate key。這時候就要在toMap方法中指定當key沖突時key的選擇。(這里是選擇第二個key覆蓋第一個key)

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}

用groupingBy 或者 partitioningBy進行分組
根據一個字段或者屬性分組也可以直接用groupingBy方法,很方便。

Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).limit(100).collect(Collectors.groupingBy(Person::getAge));
Iterator it = personGroups.entrySet().iterator();
while (it.hasNext()) {
 Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
 System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
}

使用guava

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

有時候,希望得到的map的值不是對象,而是對象的某個屬性,那么可以用下面的方式:

Map<Long, String> maps = userList.stream().collect(Collectors.toMap(User::getId, User::getAge, (key1, key2) -> key2));

 


免責聲明!

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



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