# Java8 Stream（8）List集合统计 求和 最大值 最小值 平均值

``````pigs.add(new Pig(1, "猪爸爸", 31, "M", false));
pigs.add(new Pig(2, "猪妈妈", 28, "F", true));
pigs.add(new Pig(3, "乔治", 2, "M", false));
pigs.add(new Pig(4, "佩奇", 5, "F", false));
``````

# 一、统计个数

``````long count = pigs.stream().filter(a -> a.getAge() > 5).count();
System.out.println("age > 5的人数 = " + count);
``````

# 二、利用数值流自带的函数

``````long count = pigs.stream().mapToInt(Pig::getAge).count();
int sumAge = pigs.stream().mapToInt(Pig::getAge).sum();
int maxAge = pigs.stream().mapToInt(Pig::getAge).max().getAsInt();
int minAge = pigs.stream().mapToInt(Pig::getAge).min().getAsInt();
double avgAge = pigs.stream().mapToInt(Pig::getAge).average().getAsDouble();
``````

# 三、summaryStatistics统计

``````IntSummaryStatistics statistics = pigs.stream().mapToInt(Pig::getAge).summaryStatistics();

System.out.println("count = " + statistics.getCount());
System.out.println("sumAge = " + statistics.getSum());
System.out.println("maxAge = " + statistics.getMax());
System.out.println("minAge = " + statistics.getMin());
System.out.println("avgAge = " + statistics.getAverage());
``````

# 四、利用Collectors

## 1. 对象流

``````Optional<Pig> pigMaxAgeOptional = pigs.stream().collect(Collectors.maxBy(comparing(Pig::getAge)));
if (pigMaxAgeOptional.isPresent()){
System.out.println("age最大的猪 = " + pigMaxAgeOptional.get());
}

Optional<Pig> pigMinAgeOptional = pigs.stream().collect(Collectors.minBy(comparing(Pig::getAge)));
if (pigMinAgeOptional.isPresent()){
System.out.println("age最小的猪 = " + pigMinAgeOptional.get());
}
``````

``````age最大的猪 = Pig(id=1, name=猪爸爸, age=31, gender=M, valid=false)
age最小的猪 = Pig(id=3, name=乔治, age=2, gender=M, valid=false)
``````

## 2. 数值流

Collections还提高了max、min

``````Set<Integer> ageSet = pigs.stream().map(Pig::getAge).collect(Collectors.toSet());

System.out.println("maxAge=" + Collections.max(ageSet));
System.out.println("minAge=" + Collections.min(ageSet));
``````

## 3. List<Map<String, Object>>上排序

``````List<Map<String, Object>> cats = new ArrayList<>();
Map<String,Object> cat1 = new HashMap<>();
cat1.put("name", "cat1");
cat1.put("age", 10);

Map<String,Object> cat2 = new HashMap<>();
cat2.put("name", "cat2");
cat2.put("age", 2);