java8之CollectorsAPI详解(带实例)01

这是写给自己的避免忘了:

首先我我们需要一个类:

public class Dish {

    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;

    public Dish(String name, boolean vegetarian, int calories, Type type) {
        this.name = name;
        this.vegetarian = vegetarian;
        this.calories = calories;
        this.type = type;
    }


    public String getName() {
        return name;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public int getCalories() {
        return calories;
    }

    public Type getType() {
        return type;
    }

    public enum Type {MEAT, FISH, OTHER}


    @Override
    public String toString() {
        return "Dish{" +
                "name='" + name + '\'' +
                ", vegetarian=" + vegetarian +
                ", calories=" + calories +
                ", type=" + type +
                '}';
    }
}

先实例化:\

public 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),
        new Dish("rice", true, 350, Dish.Type.OTHER),
        new Dish("season fruit", true, 120, Dish.Type.OTHER),
        new Dish("pizza", true, 550, Dish.Type.OTHER),
        new Dish("prawns", false, 300, Dish.Type.FISH),
        new Dish("salmon", false, 450, Dish.Type.FISH));

java8之CollectorsAPI详解(带实例)01

介绍的API都附在了上面的图里面: 

1,这个意思是吧Dish里面的Calories里面算出平均数

private static void testAveragingDouble() {
    System.out.println("testAveragingDouble");
    Optional.ofNullable(menu.stream().collect(Collectors.averagingDouble(Dish::getCalories)))
            .ifPresent(System.out::println);
}
private static void testAveragingInt() {
    System.out.println("testAveragingDouble");
    Optional.ofNullable(menu.stream().collect(averagingInt(Dish::getCalories)))
            .ifPresent(System.out::println);
}

private static void testAveragingLong() {
    System.out.println("testAveragingDouble");
    Optional.ofNullable(menu.stream().collect(averagingInt(Dish::getCalories)))
            .ifPresent(System.out::println);
}

上面这个的类意思一样只不过是他们的类型变了而已:输出结果:

CollectingAndThen

在用这个之前我们先举个栗子:

List<Dish> collect = menu.stream().filter(d -> d.getType().equals(Dish.Type.OTHER)).collect(toList());

collect.add(new Dish("", false, 100, Dish.Type.OTHER));
System.out.println(collect);

熟悉java8 的人都知道,这段代码的意思是,先把type为other的类型过滤取来,我们想输出,但是下面有坐了一个操作把一个新对象添加进去, 那么我们应该怎么避免这样的方法呢?

List<Dish> collect1 = menu.stream().filter
        (d -> d.getType().equals(Dish.Type.OTHER)).
        collect(collectingAndThen(toList(), 
                Collections::unmodifiableList));
这里我便用到了这个Api,跟上面的一比我们就知道它怎么用,就是当toList(),操作完之后,想对的,他还能用
  Collections::unmodifiableList

来操作toList()返回的结果.

java8之CollectorsAPI详解(带实例)01

很显然当我门在执行这段代码的话,就会报错,因为我们在collectingAndThen 之后给它限制不能在添加,所以当执行添加操作的时候就报错了

在执行下面这个例子:

private static void testcollectingAndThen() {
    System.out.println("testcollectingAndThen");
    Optional.ofNullable(menu.stream().collect(Collectors.
            collectingAndThen(averagingInt(Dish::getCalories),
                    a -> "CAlumniate" + a)))
            .ifPresent(System.out::println);

上面我们的意思就是执行完get之后,在执行了一句输出 :输出结果

CAlumniate466.6666666666667  

下个API:

private static void testcounting() {
    System.out.println("counting");
    Optional.of(menu.stream()
            .collect(Collectors.counting()))
            .ifPresent(System.out::println);
}

这个也就是计算啦输出结果:

counting

9

//分组
private static void testGroupingByFunction() {
    System.out.println("testGroupingByFunction");
    Optional.ofNullable(menu.stream().
            collect(Collectors.groupingBy(Dish::getType))).
            ifPresent(System.out::println);
}

上一节讲过了.分组

//分组后计算 ,分组后平均值
private static void testGroupingByFunctionAndCollector() {
    System.out.println("testGroupingByFunctionAndCollector");
    Optional.ofNullable(menu.stream().collect(Collectors.
            groupingBy(Dish::getType,
                    Collectors.averagingInt(Dish::getCalories))))
            .ifPresent(System.out::println);
}

groupingBy里面可以有两个参数自行理解

private static void testGroupingByFunctionAndSupplierAndCollector() {
    //本来返回有个map
    Map<Dish.Type, Double> map = menu.stream().collect(Collectors.groupingBy(Dish::getType, Collectors.averagingInt(Dish::getCalories)));
    //先在要返回一个treemap
    Map<Dish.Type, Double> collect = menu.stream().collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingInt(Dish::getCalories)));
    Optional.of(map.getClass()).ifPresent(System.out::println);
    Optional.of(collect.getClass()).ifPresent(System.out::println);
}

groupingBy里面可以有三个参数自行理解意思:

也就是我们把hashmap类型转化成TreeMap类型.......................

private static void testSummarizingInt() {
    System.out.println("testSummarizingInt");
    IntSummaryStatistics collect = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));
    Optional.ofNullable(collect).ifPresent(System.out::println);
}

这个就牛逼了..............................

输出如下:

IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}

也就是说吧它的和,最大,最小,平均值,一下都算出来了,好牛逼啊啊啊啊

未待完毕................................