https://blog.csdn.net/zlj1217/article/details/81611834java
背景
在最近的工做開發之中,慢慢習慣了不少Java8中的Stream的用法,很方便並且也能夠並行的去執行這個流,這邊去寫一下昨天遇到的一個list轉map的場景。
list轉map在Java8中stream的應用
經常使用方式
1.利用Collectors.toMap方法進行轉換api
public Map<Long, String> getIdNameMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
}
1
2
3
其中第一個參數就是能夠,第二個參數就是value的值。ide
2.收集對象實體自己
- 在開發過程當中咱們也須要有時候對本身的list中的實體按照其中的一個字段進行分組(好比 id ->List),這時候要設置map的value值是實體自己。函數
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}
1
2
3
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));
}
1
2
3
用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());
}
1
2
3
4
5
6
7
8
partitioningBy能夠理解爲特殊的groupingBy,key值爲true和false,固然此時方法中的參數爲一個判斷語句(用於判斷的函數式接口)
Map<Boolean, List<Person>> children = Stream.generate(new PersonSupplier()).
limit(100).
collect(Collectors.partitioningBy(p -> p.getAge() < 18));
System.out.println("Children number: " + children.get(true).size());
System.out.println("Adult number: " + children.get(false).size());
1
2
3
4
5
關於stream使用的好文推薦:
這裏去看了ibm的一篇關於stream的文章,get到了很多stream還沒遇到過的用法。老鐵們能夠去學習一下。[https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/ ]
---------------------
做者:zlj1217
來源:CSDN
原文:https://blog.csdn.net/zlj1217/article/details/81611834
版權聲明:本文爲博主原創文章,轉載請附上博文連接!.net