java stream中Collectors的用法實例精講
簡介
在java stream中,我們通常需要將處理后的stream轉(zhuǎn)換成集合類,這個時候就需要用到stream.collect方法。collect方法需要傳入一個Collector類型,要實現(xiàn)Collector還是很麻煩的,需要實現(xiàn)好幾個接口。
于是java提供了更簡單的Collectors工具類來方便我們構(gòu)建Collector。
下面我們將會具體講解Collectors的用法。
假如我們有這樣兩個list:
List<String> list = Arrays.asList("jack", "bob", "alice", "mark");
List<String> duplicateList = Arrays.asList("jack", "jack", "alice", "mark");上面一個是無重復(fù)的list,一個是帶重復(fù)數(shù)據(jù)的list。接下來的例子我們會用上面的兩個list來講解Collectors的用法。
Collectors.toList()
List<String> listResult = list.stream().collect(Collectors.toList());
log.info("{}",listResult);將stream轉(zhuǎn)換為list。這里轉(zhuǎn)換的list是ArrayList,如果想要轉(zhuǎn)換成特定的list,需要使用toCollection方法。
Collectors.toSet()
Set<String> setResult = list.stream().collect(Collectors.toSet());
log.info("{}",setResult);toSet將Stream轉(zhuǎn)換成為set。這里轉(zhuǎn)換的是HashSet。如果需要特別指定set,那么需要使用toCollection方法。
因為set中是沒有重復(fù)的元素,如果我們使用duplicateList來轉(zhuǎn)換的話,會發(fā)現(xiàn)最終結(jié)果中只有一個jack。
Set<String> duplicateSetResult = duplicateList.stream().collect(Collectors.toSet());
log.info("{}",duplicateSetResult);Collectors.toCollection()
上面的toMap,toSet轉(zhuǎn)換出來的都是特定的類型,如果我們需要自定義,則可以使用toCollection()
List<String> custListResult = list.stream().collect(Collectors.toCollection(LinkedList::new));
log.info("{}",custListResult);上面的例子,我們轉(zhuǎn)換成了LinkedList。
Collectors.toMap()
toMap接收兩個參數(shù),第一個參數(shù)是keyMapper,第二個參數(shù)是valueMapper:
Map<String, Integer> mapResult = list.stream()
.collect(Collectors.toMap(Function.identity(), String::length));
log.info("{}",mapResult);如果stream中有重復(fù)的值,則轉(zhuǎn)換會報IllegalStateException異常:
Map<String, Integer> duplicateMapResult = duplicateList.stream()
.collect(Collectors.toMap(Function.identity(), String::length));怎么解決這個問題呢?我們可以這樣:
Map<String, Integer> duplicateMapResult2 = duplicateList.stream()
.collect(Collectors.toMap(Function.identity(), String::length, (item, identicalItem) -> item));
log.info("{}",duplicateMapResult2);在toMap中添加第三個參數(shù)mergeFunction,來解決沖突的問題。
Collectors.collectingAndThen()
collectingAndThen允許我們對生成的集合再做一次操作。
List<String> collectAndThenResult = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toList(), l -> {return new ArrayList<>(l);}));
log.info("{}",collectAndThenResult);Collectors.joining()
Joining用來連接stream中的元素:
String joinResult = list.stream().collect(Collectors.joining());
log.info("{}",joinResult);
String joinResult1 = list.stream().collect(Collectors.joining(" "));
log.info("{}",joinResult1);
String joinResult2 = list.stream().collect(Collectors.joining(" ", "prefix","suffix"));
log.info("{}",joinResult2);可以不帶參數(shù),也可以帶一個參數(shù),也可以帶三個參數(shù),根據(jù)我們的需要進行選擇。
Collectors.counting()
counting主要用來統(tǒng)計stream中元素的個數(shù):
Long countResult = list.stream().collect(Collectors.counting());
log.info("{}",countResult);Collectors.summarizingDouble/Long/Int()
SummarizingDouble/Long/Int為stream中的元素生成了統(tǒng)計信息,返回的結(jié)果是一個統(tǒng)計類:
IntSummaryStatistics intResult = list.stream()
.collect(Collectors.summarizingInt(String::length));
log.info("{}",intResult);輸出結(jié)果:
22:22:35.238 [main] INFO com.flydean.CollectorUsage - IntSummaryStatistics{count=4, sum=16, min=3, average=4.000000, max=5}
Collectors.averagingDouble/Long/Int()
averagingDouble/Long/Int()對stream中的元素做平均:
Double averageResult = list.stream().collect(Collectors.averagingInt(String::length));
log.info("{}",averageResult);Collectors.summingDouble/Long/Int()
summingDouble/Long/Int()對stream中的元素做sum操作:
Double summingResult = list.stream().collect(Collectors.summingDouble(String::length));
log.info("{}",summingResult);Collectors.maxBy()/minBy()
maxBy()/minBy()根據(jù)提供的Comparator,返回stream中的最大或者最小值:
Optional<String> maxByResult = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder()));
log.info("{}",maxByResult);Collectors.groupingBy()
GroupingBy根據(jù)某些屬性進行分組,并返回一個Map:
Map<Integer, Set<String>> groupByResult = list.stream()
.collect(Collectors.groupingBy(String::length, Collectors.toSet()));
log.info("{}",groupByResult);Collectors.partitioningBy()
PartitioningBy是一個特別的groupingBy,PartitioningBy返回一個Map,這個Map是以boolean值為key,從而將stream分成兩部分,一部分是匹配PartitioningBy條件的,一部分是不滿足條件的:
Map<Boolean, List<String>> partitionResult = list.stream()
.collect(Collectors.partitioningBy(s -> s.length() > 3));
log.info("{}",partitionResult);看下運行結(jié)果:
22:39:37.082 [main] INFO com.flydean.CollectorUsage - {false=[bob], true=[jack, alice, mark]}
結(jié)果被分成了兩部分。
總結(jié)
Collectors是一個非常強大的工具類,希望大家能夠靈活使用。
本文的例子https://github.com/ddean2009/learn-java-streams/tree/master/Collectors
以上就是java stream中Collectors的用法實例精講的詳細內(nèi)容,更多關(guān)于java stream Collector的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Java多態(tài)對象的類型轉(zhuǎn)換與動態(tài)綁定
這篇文章主要介紹了詳解Java多態(tài)對象的類型轉(zhuǎn)換與動態(tài)綁定,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
java中調(diào)用GDAL DLL的實現(xiàn)方法
本篇文章是對java中調(diào)用GDAL DLL的實現(xiàn)方法進行了詳細的分析介紹,需要的朋友參考下2013-05-05
關(guān)于各種排列組合java算法實現(xiàn)方法
這篇文章介紹了幾種用JAVA實現(xiàn)的排列組合算法,有需要的朋友可以參考一下2013-06-06
springboot + jpa實現(xiàn)刪除數(shù)據(jù)的操作代碼
這篇文章主要介紹了springboot + jpa實現(xiàn)刪除數(shù)據(jù)的操作代碼,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-05-05
Java?-jar參數(shù)設(shè)置小結(jié)
本文主要介紹了Java?-jar參數(shù)設(shè)置小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
SpringBoot使用@Cacheable注解實現(xiàn)緩存功能流程詳解
最近一直再學(xué)Spring Boot,在學(xué)習(xí)的過程中也有過很多疑問。為了解答自己的疑惑,也在網(wǎng)上查了一些資料,以下是對@Cacheable注解的一些理解2023-01-01

