/**
*
*/
package com.gewb.stream;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
/**
* @author Bingo.Ge
* @date 2020年7月3日
*/
public class CollectorsAction {
private final static List<Dish> menu = Arrays.asList(
new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER));
public static void main(String[] args) {
testAverageingDouble();
testCollectingAndThen();
testGroupByFunction();
testSummarizingInt();
}
private static void testAverageingDouble() {
System.out.println("===================testAverageingDouble===================");
Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories))).ifPresent(System.out::println);
}
private static void testCollectingAndThen() {
System.out.println("===================testCollectingAndThen===================");
Optional.ofNullable(menu.stream().collect(Collectors
.collectingAndThen(Collectors.averagingInt(Dish::getCalories), a -> "average calories is:" + a)))
.ifPresent(System.out::println);
}
private static void testGroupByFunction() {
System.out.println("===================testGroupByFunction===================");
Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.counting()))).ifPresent(System.out::println);
}
private static void testSummarizingInt() {
System.out.println("===================testSummarizingInt===================");
Optional.ofNullable(menu.stream().collect(Collectors.summarizingInt(Dish::getCalories))).ifPresent(System.out::println);
}
}
输出结果:
===================testAverageingDouble=================== 607.5 ===================testCollectingAndThen=================== average calories is:607.5 ===================testGroupByFunction=================== {MEAT=3, OTHER=1} ===================testSummarizingInt=================== IntSummaryStatistics{count=4, sum=2430, min=400, average=607.500000, max=800}