1.Collectors.toList()
:轉換成List集合。/ Collectors.toSet()
:轉換成set集合。
System.out.println(Stream.of("a", "b", "c","a").collect(Collectors.toSet()));
2.Collectors.toCollection(TreeSet::new)
:轉換成特定的set集合。
TreeSet<String> treeSet = Stream.of("a", "c", "b", "a").collect(Collectors.toCollection(TreeSet::new)); System.out.println(treeSet);
3.
Collectors.toMap(keyMapper, valueMapper, mergeFunction)
:轉換成map。
Map<String, String> collect = Stream.of("a", "b", "c", "a").collect(Collectors.toMap(x -> x, x -> x + x,(oldVal, newVal) -> newVal)));
collect.forEach((k,v) -> System.out.println(k + ":" + v));
補充
關於合並函數 BinaryOperator<U> mergeFunction
對象
當toMap中沒有用合並函數時,出現key重復時,會拋出異常 : Exception in thread "main" java.lang.IllegalStateException: Duplicate key aa
當使用合並函數時,可通過Labmda表達式,對重復值進行處理
4.Collectors.minBy(Integer::compare)
:求最小值,相對應的當然也有maxBy方法。
5.Collectors.averagingInt(x->x)
:求平均值,同時也有averagingDouble、averagingLong方法。
6.Collectors.summingInt(x -> x))
:求和。
7.Collectors.summarizingDouble(x -> x)
:可以獲取最大值、最小值、平均值、總和值、總數。
DoubleSummaryStatistics summaryStatistics = Stream.of(1, 3, 4).collect(Collectors.summarizingDouble(x -> x));
System.out.println(summaryStatistics .getAverage());
8. Collectors.groupingBy(x -> x)
:有三種方法,查看源碼可以知道前兩個方法最終調用第三個方法,
第二個參數默認HashMap::new
第三個參數默認Collectors.toList()
Map<Integer, List<Integer>> map = Stream.of(1, 3, 3, 2).collect(Collectors.groupingBy(Function.identity())); System.out.println(map);
Map<Integer, Integer> map1 = Stream.of(1, 3, 3, 2).collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(x -> x))); System.out.println(map1);
HashMap<Integer, List<Integer>> hashMap = Stream.of(1, 3, 3, 2).collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.mapping(x -> x + 1, Collectors.toList()))); System.out.println(hashMap);
補充: identity()是Function類的靜態方法,和 x->x 是一個意思,
當僅僅需要自己返回自己時,使用identity()能更清楚的表達作者的意思.
寫的復雜一點,繞一點,對理解很有好處.下邊是運行結果:
9.Collectors.partitioningBy(x -> x > 2)
,把數據分成兩部分,key為ture/false
。第一個方法也是調用第二個方法,第二個參數默認為Collectors.toList()
Map<Boolean, List<Integer>> map = Stream.of(1, 3, 3, 2).collect(Collectors.partitioningBy(x -> x > 2)); Map<Boolean, Long> longMap = Stream.of(1, 3, 3, 2).collect(Collectors.partitioningBy(x -> x > 1, Collectors.counting()));
10.Collectors.joining(",")
:拼接字符串。
System.out.println(Stream.of("1", "3", "3", "2").collect(Collectors.joining(",")));
11.
Collectors.collectingAndThen(Collectors.toList(), x -> x.size()):先執行collect操作后再執行第二個參數的表達式。這里是先塞到集合,再得出集合長度。
Integer integer = Stream.of("1", "2", "3").collect(Collectors.collectingAndThen(Collectors.toList(), x -> x.size()));
12.Collectors.mapping(...)
:跟Stream的map操作類似,只是參數有點區別
System.out.println(Stream.of(1, 3, 5).collect(Collectors.mapping(x -> x + 1, Collectors.toList())));