---
title: "Collectors - Demo2"
author: "fairy_xzc"
date: "2018-07-01T22:32:23Z"
tags: []
categories: ["编程语言"]
slug: "collectors-demo2"
draft: false
lastmod: "2018-07-01T22:21:08Z"
id: 2425963
url: "https://agilestyle.iteye.com/blog/2425963"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2425963](/blog/2425963)**

 

## Outline

testAveragingDouble();

testAveragingInt();

testAveragingLong();

testCollectingAndThen1();

testCollectingAndThen2();

testCounting();

testGroupingByFunction1();

testGroupingByFunction2();

testGroupingByFunction3();

testSummarizingInt();

 

## SRC

```
package org.fool.java8.collector;

import java.util.Arrays;
import java.util.Collections;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
import java.util.stream.Collectors;

public class CollectorsTest {

    private 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) );

    public static void main(String[] args) {
        testAveragingDouble();
        testAveragingInt();
        testAveragingLong();
        testCollectingAndThen1();
        testCollectingAndThen2();
        testCounting();
        testGroupingByFunction1();
        testGroupingByFunction2();
        testGroupingByFunction3();
        testSummarizingInt();
    }

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

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

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

    private static void testCollectingAndThen1() {
        Optional.ofNullable(menu.stream().
                collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), a -> "The average calories is " + a))).
                ifPresent(System.out::println);
    }

    private static void testCollectingAndThen2() {
        List<Dish> result = menu.stream().
                filter(d -> d.getType().equals(Dish.Type.MEAT)).
                collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));

        //result.add(new Dish("", false, 100, Dish.Type.OTHER));

        System.out.println(result);
    }

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

    private static void testGroupingByFunction1() {
        Optional.ofNullable(menu.stream().collect(Collectors.groupingBy(Dish::getType))).ifPresent(System.out::println);
    }

    private static void testGroupingByFunction2() {
        Optional.ofNullable(menu.stream().
                collect(Collectors.groupingBy(Dish::getType, Collectors.counting()))).
                ifPresent(System.out::println);
    }

    private static void testGroupingByFunction3() {
       Map<Dish.Type, Double> map = menu.stream().
                collect(Collectors.groupingBy(Dish::getType, TreeMap::new, Collectors.averagingInt(Dish::getCalories)));

       Optional.of(map.getClass()).ifPresent(System.out::println);
       Optional.of(map).ifPresent(System.out::println);
    }

    private static void testSummarizingInt() {
        IntSummaryStatistics result = menu.stream().collect(Collectors.summarizingInt(Dish::getCalories));

        Optional.of(result).ifPresent(System.out::println);
    }

    public static class Dish {
        private String name;
        private boolean vegetarian;
        private int calories;
        private 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 enum Type { MEAT, FISH, OTHER }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public boolean isVegetarian() {
            return vegetarian;
        }

        public void setVegetarian(boolean vegetarian) {
            this.vegetarian = vegetarian;
        }

        public int getCalories() {
            return calories;
        }

        public void setCalories(int calories) {
            this.calories = calories;
        }

        public Type getType() {
            return type;
        }

        public void setType(Type type) {
            this.type = type;
        }

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

}
```

## Console Output

```
466.6666666666667
466.6666666666667
466.6666666666667
The average calories is 466.6666666666667
[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}]
9
{OTHER=[Dish{name='french fries', vegetarian=true, calories=530, type=OTHER}, Dish{name='rice', vegetarian=true, calories=350, type=OTHER}, Dish{name='season fruit', vegetarian=true, calories=120, type=OTHER}, Dish{name='pizza', vegetarian=true, calories=550, type=OTHER}], FISH=[Dish{name='prawns', vegetarian=false, calories=300, type=FISH}, Dish{name='salmon', vegetarian=false, calories=450, type=FISH}], MEAT=[Dish{name='pork', vegetarian=false, calories=800, type=MEAT}, Dish{name='beef', vegetarian=false, calories=700, type=MEAT}, Dish{name='chicken', vegetarian=false, calories=400, type=MEAT}]}
{OTHER=4, FISH=2, MEAT=3}
class java.util.TreeMap
{MEAT=633.3333333333334, FISH=375.0, OTHER=387.5}
IntSummaryStatistics{count=9, sum=4200, min=120, average=466.666667, max=800}
```