標籤:add array cin count 收集 nbsp sys 使用者 print
一、R collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
supplier:一個能創造目標類型執行個體的方法。
accumulator:一個將當元素添加到目標中的方法。
combiner:一個將中間狀態的多個結果整合到一起的方法(並發的時候會用到)
List result = stream.collect(() -> new ArrayList<>(), (list, item) -> list.add(item), (one, two) -> one.addAll(two));
二、R collect(Collector collector)
Collector其實是上面supplier、accumulator、combiner的彙總體。那麼上面代碼就變成:
List list = Stream.of(1, 2, 3, 4).filter(p -> p > 2).collect(Collectors.toList());
三、collector
Collector是Stream的可變減少操作介面,Collectors(類收集器)提供了許多常見的可變減少操作的實現。
四、建立Collector
轉換成其他集合:toList、toSet、toCollection、toMap
List<Integer> collectList = Stream.of(1, 2, 3, 4) .collect(Collectors.toList());System.out.println("collectList: " + collectList);// 列印結果// collectList: [1, 2, 3, 4]
轉成值:
使用collect可以將Stream轉換成值。maxBy和minBy允許使用者按照某個特定的順序產生一個值。
-
-
- averagingDouble:求平均值,Stream的元素類型為double
- averagingInt:求平均值,Stream的元素類型為int
- averagingLong:求平均值,Stream的元素類型為long
- counting:Stream的元素個數
- maxBy:在指定條件下的,Stream的最大元素
- minBy:在指定條件下的,Stream的最小元素
- reducing: reduce操作
- summarizingDouble:統計Stream的資料(double)狀態,其中包括count,min,max,sum和平均。
- summarizingInt:統計Stream的資料(int)狀態,其中包括count,min,max,sum和平均。
- summarizingLong:統計Stream的資料(long)狀態,其中包括count,min,max,sum和平均。
- summingDouble:求和,Stream的元素類型為double
- summingInt:求和,Stream的元素類型為int
- summingLong:求和,Stream的元素類型為long
Optional<Integer> collectMaxBy = Stream.of(1, 2, 3, 4) .collect(Collectors.maxBy(Comparator.comparingInt(o -> o)));System.out.println("collectMaxBy:" + collectMaxBy.get());// 列印結果// collectMaxBy:4分割資料區塊:Collectors.partitioningBy
Map<Boolean, List<Integer>> collectParti = Stream.of(1, 2, 3, 4) .collect(Collectors.partitioningBy(it -> it % 2 == 0));System.out.println("collectParti : " + collectParti);// 列印結果// collectParti : {false=[1, 3], true=[2, 4]}
資料分組:Collectors.groupingBy
Map<Boolean, List<Integer>> collectGroup= Stream.of(1, 2, 3, 4) .collect(Collectors.groupingBy(it -> it > 3));System.out.println("collectGroup : " + collectGroup);// 列印結果// collectGroup : {false=[1, 2, 3], true=[4]}
字串:Collectors.joining
String strJoin = Stream.of("1", "2", "3", "4") .collect(Collectors.joining(",", "[", "]"));System.out.println("strJoin: " + strJoin);// 列印結果// strJoin: [1,2,3,4]
[java]Stream API——collect