工廠方法 返回類型 用 於
toList List<T> 把流中所有項目收集到一個List
使用示例:List<Dish> dishes = menuStream.collect(toList());
toSet Set<T> 把流中所有項目收集到一個Set,刪除重復項
使用示例:Set<Dish> dishes = menuStream.collect(toSet());
toCollection Collection<T> 把流中所有項目收集到給定的供應源創建的集合
使用示例:Collection<Dish> dishes = menuStream.collect(toCollection(),ArrayList::new);
counting Long 計算流中元素的個數
使用示例:long howManyDishes = menuStream.collect(counting());
summingInt Integer 對流中項目的一個整數屬性求和
使用示例:int totalCalories =menuStream.collect(summingInt(Dish::getCalories));
averagingInt Double 計算流中項目Integer 屬性的平均值
使用示例:double avgCalories =menuStream.collect(averagingInt(Dish::getCalories));
summarizingInt IntSummaryStatistics 收集關於流中項目Integer 屬性的統計值,例如最大、最小、總和與平均值
使用示例:IntSummaryStatistics menuStatistics =menuStream.collect(summarizingInt(Dish::getCalories));
joining` String 連接對流中每個項目調用toString 方法所生成的字符串
使用示例:String shortMenu =menuStream.map(Dish::getName).collect(joining(", "));
maxBy Optional<T> 一個包裹了流中按照給定比較器選出的最大元素的Optional,或如果流為空則為Optional.empty()
使用示例:Optional<Dish> fattest =menuStream.collect(maxBy(comparingInt(Dish::getCalories)));
minBy Optional<T> 一個包裹了流中按照給定比較器選出的最小元素的Optional,或如果流為空則為Optional.empty()
使用示例:Optional<Dish> lightest =menuStream.collect(minBy(comparingInt(Dish::getCalories)));
reducing 歸約操作產生的類型 從一個作為累加器的初始值開始,利用BinaryOperator 與流中的元素逐個結合,從而將流歸約為單個值
使用示例:int totalCalories =menuStream.collect(reducing(0, Dish::getCalories, Integer::sum));
collectingAndThen 轉換函數返回的類型 包裹另一個收集器,對其結果應用轉換函數
使用示例:int howManyDishes =menuStream.collect(collectingAndThen(toList(), List::size));
groupingBy Map<K, List<T>> 根據項目的一個屬性的值對流中的項目作問組,並將屬性值作為結果Map 的鍵
使用示例:Map<Dish.Type,List<Dish>> dishesByType =menuStream.collect(groupingBy(Dish::getType));
partitioningBy Map<Boolean,List<T>> 根據對流中每個項目應用謂詞的結果來對項目進行分區
使用示例:Map<Boolean,List<Dish>> vegetarianDishes =menuStream.collect(partitioningBy(Dish::isVegetarian));