用流收集數(shù)據(jù)
匯總
long howManyDishes = menu.stream().collect(Collectors.counting());
int totalCalories = menu.stream().collect(summingInt(Dish::getCalories));
//求平均值
double avgCalories = menu.stream().collect(averagingInt(Dish::getCalories));
//summarizing操作可以得到總和.平均值.最大值.最小值
IntSummaryStatistics menuStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
//打印可得
IntSummaryStatistics{count= 9,sum=4300,min=120,average=477.777,max = 800};
查找最大值和最小值
Comparator<Dish> dishCaloriesComparator = Comparator.comparingInt(Dish::getCalories);
Optional<Dish> mostCalorieDish = menu.stream().collect(maxBy(dishCaloriesComparator));
連接字符串
//joining在內(nèi)部使用了StringBuilder來把生成的字符串逐個追加起來
String shortMenu = menu.stream().map(Dish::getName).collect(joning());
//用逗號分隔
String shortMenu2 = menu.stream().map(Dish::getName).collect(joning(","));
廣義的歸約匯總
int totalCalories = menu.stream().collect(reducing(0,Dish::getCalories,(i,j)->j+i));
reducing需要說那個參數(shù):
1.起始值
2.被操作的值
3.是一個BinaryOperator,將兩個項目累計成一個同類型的值
同理,可以求最高熱量的菜
Optional<Dish> mostCalorieDish = menu.stream().collect(reducing(d1,d2)->d1.getCalories()>d2.getCalories()?d1:d2));
分組
Map<Dish.Type,List<Dish> dishesByType = menu.stream().collect(groupingBy(Dish::getType));
復(fù)雜的分組
public enum CaloricLevel{DIET,NORMAL,FAT}
Map<CaloricLevel,List<Dish>> dishesByCaloricLevel = menu.stream().collect(
groupingBy(dish ->{
if(dish.getCalories()<=400) return CaloricLevel.DIET;
else if(dish.getCalories() <= 700) return CaloricLevel.NORMAL:
else return CaloricLevel.FAT;
})
);
按子組收集數(shù)據(jù)
Map<Dish.Type,Long> typesCount = menu.stream().collect(
groupingBy(Dish::getType,counting()));
1.查找每個子組中熱量最高的Dish
Map<Dish.Type,Dish> mostCaloricByType = menu.stream().collect(groupingBy(Dish::getType,collectingAndThen(
maxBy(comparingInt(Dish::getCalories)),Optional::get)));
2.對每組進(jìn)行求和
Map<Dish.Type,Integer> totalCaloriesByType = menu.stream().collect(groupingBy(Dish::getType,summingInt(Dish::getCalories)));
3.groupingBy和mapping收集器結(jié)合起來
Map<Dish.Type,Set<CaloricLevel>> caloricLevelsByType = menu.stream().collect(
groupingBy(Dish::getType,mapping(
dish -> {
if(dish.getCalories()<=400) return CaloricLevel.DIET;
else if (dish.getCalories <= 700) return CaloricLevel.NORMAL;
else return CaloricLevel.FAT,toSet()
}
))
);
分區(qū):
Map<Boolean , List<Dish>> partitionedMenu = menu.stream().collect(partitioningBy(Dish::isVegetarian));
partitioningBy工廠方法有一個重載版本,可以傳遞第二收集器
Map<Boolean,Map<Dish.Type,List<Dish>>> vegetarianDishesByType = menu.stream().collect(
partitioningBy(Dish::isVegetarian,groupingBy(Dish::getType)));
還可以重用前面的代碼來找到素食和非素食中熱量最高的菜:
Map<Boolean, Dish> mostVegetarian = menu.stream().collect(
menu.stream().collect(
partitioningBy(Dish::isVegetarian,
collectingAndThe(
maxBy(comparingInt(Dish::getCalories)),
Optional::get))));
將數(shù)字按質(zhì)數(shù)和非質(zhì)數(shù)分區(qū)
public boolean isPrime(int candidate){
return IntStream.range(2,candidate)//產(chǎn)生一個自然數(shù)范圍,從2開始,直至但不包括待測數(shù)
.noneMatch(i -> candidate % i ==0);//如果待測數(shù)字不能被流中任何數(shù)字整除則返回true
}
//一個簡單的優(yōu)化是僅測試小于等于待測數(shù)平方根因子
public boolean isPrime(int candidate) {
int candidateRoot = (int) Math.sqrt(candidate);
return IntStream.rangeClosed(2, candidate).noneMatch(i -> candidate % i == 0);
}
public Map<Boolean, List<Integer>> partitionPrimes(int n) {
return IntStream.rangeClosed(2, n).boxed().collect(partitioningBy(candidate -> isPrime(candidate)));
}
Collectors類的靜態(tài)工廠方法
| 工廠方法 | 返回類型 | 用于 |
|---|---|---|
| toList | List< T > | 把流中所有項目收集到一個List |
| List< Dish > dishes = menuStream.collect(toList()); | ||
| toSset | Set< T > | 把流中所有項目收集到一個Set,刪除重復(fù)項 |
| Set< Dish > dishes = menuStream.collect(toSet()); | ||
| toCollection | Collection< T > | 把流中所有項目收集到給定的供應(yīng)源創(chuàng)建的集合 |
| Collection< Dish > dishes = menuStream.collect(toCollection(),ArrayList::new); | ||
| counting | Long | 計算流中元素的個數(shù) |
| long howManyDishes = menuStream.collect(counting()); | ||
| summingInt | Integer | 對流中項目的一個整數(shù)屬性求和 |
| int totalCalories = menuStream.collect(summingInt(Dish::getCalories)); | ||
| averagingInt | Double | 計算流中項目Integer屬性的平均值 |
| double avgCalories = menuStream.collect(averagingInt(Dish::getCalories)); | ||
| summarizingInt | IntSummaryStatistics | 收集關(guān)于流中項目Integer屬性的統(tǒng)計值,例如最大,最小,總和與平均值 |
| IntSummaryStatistics menuStaticstics = menuStream.collect(summarizingInt(Dish::getCalories)); | ||
| joining | String | 連接對流中每個項目調(diào)用toString方法生成的字符串 |
| String shortMenu = menuStream.map(Dish::getName).collect(joining(", ")); | ||
| maxBy | Optional< T > | 選出最大元素的Optional |
| Optional< Dish > fattest = menuStream.collect(maxBy(comparingInt(Dish::getCalories))); | ||
| minBy | Optional< T > | 最小元素 |
| Optional< Dish > fattest = menuStream.collect(minBy(comparingInt(Dish::getCalories))); | ||
| reducing | 歸約操作產(chǎn)生的類型 | 利用BinaryOperator與流中的元素逐個結(jié)合,從而將流歸約為單個值 |
| int totalCalories = menuStream.collect(reducing(0,Dish::getCalories,Integer::sum)); | ||
| collectingAndThen | 轉(zhuǎn)換函數(shù)返回的類型 | 包裹另一個收集器,對其結(jié)果應(yīng)用轉(zhuǎn)換函數(shù) |
| int howManyDishes = menuStream.collect(collectingAndThe(toList(),List::size)); | ||
| groupingBy | Map< K ,List< T > > | 根據(jù)項目的一個屬性的值對流中的項目作問組,并將屬性值作為結(jié)果Map的鍵 |
| Map< Dish.Type,List< Dish>> dishesByType = menuStream.collect(groupingBy(Dish::getType)); | ||
| partitioningBy | Map< Boolean,List< T>> | 分區(qū) |
| Map< Boolean, List< t>> vegetarianDishes = menuStream.collect(partitioningBy(Dish::isVegetarian)); | ||