1.说明
聚合操作主要包括 : 求最大值、最小值、求和、求平均值、求数量
本篇文章,主要是通过阅读代码
的方式了解具体的使用,核心代码是2.2节
* 对Stream中的数据做聚合计算
* 1.最大值
* .collect(Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge()));
* 2.最小值
* .collect(Collectors.minBy((s1, s2) -> s1.getAge() - s2.getAge()));
* 3.求和
* .collect(Collectors.summingInt(student -> student.getAge()));
* .collect(Collectors.summingInt(Student::getAge));
* 4.求平均
* .collect(Collectors.averagingDouble(student -> student.getAge()));
* .collect(Collectors.averagingDouble(Student::getAge));
* 5.统计数量
* .collect(Collectors.counting());
2.代码
2.1 定义一个普通类
/**
* 一个类,配合集合的流式处理
*/
class Student{
private String name;
private Integer age;
public Student() {
}
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
// 此处省略了 getter/setter 方法
/**
* 重写一下 equals 方法
* @param o
* @return
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(name, student.name) &&
Objects.equals(age, student.age);
}
/**
* 重写一下 hashCode
* @return
*/
@Override
public int hashCode() {
return Objects.hash(name, age);
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2.2 主测试代码
package com.northcastle.I_stream;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;
public class StreamCollect02 {
public static void main(String[] args) {
//1.准备一个List集合作为元数据
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("盖聂",20));
studentList.add(new Student("小庄",10));
studentList.add(new Student("盖聂",20));
studentList.add(new Student("天明",8));
//1.求集合中年龄最大的对象
Optional<Student> maxStudent = studentList.stream()
.collect(Collectors.maxBy((s1, s2) -> s1.getAge() - s2.getAge()));
System.out.println("maxStudent = "+maxStudent.get());
//2.求集合中年龄最小的对象
Optional<Student> minStudent = studentList.stream()
.collect(Collectors.minBy((s1, s2) -> s1.getAge() - s2.getAge()));
System.out.println("minStudent = "+minStudent.get());
//3.求年龄的和
Integer sumAge = studentList.stream()
//.collect(Collectors.summingInt(student -> student.getAge()));
.collect(Collectors.summingInt(Student::getAge));
System.out.println("sumAge = "+sumAge);
//4.求年龄的平均值
Double avgAge = studentList.stream()
//.collect(Collectors.averagingDouble(student -> student.getAge()));
.collect(Collectors.averagingDouble(Student::getAge));
System.out.println("avgAge = "+avgAge);
//5.统计数量
Long countNum = studentList.stream()
.collect(Collectors.counting());
System.out.println("countNum = "+countNum);
}
}
2.3 运行结果
3.完成
Congratulations!
You are one step closer to success!