这是我参与8月更文挑战的第28天,活动详情查看:8月更文挑战
@[TOC](Stream reduce聚合计算方法)
reduce是一种聚合操作,聚合的含义就是将多个值经过特定计算之后得到单个值, 常见的 count 、sum 、avg 、max 、min 等函数就是一种聚合操作。
reduce 方法介绍
A: Optional reduce(BinaryOperator accumulator);
参数: BinaryOperator accumulator , BinaryOperator 继承于 BiFunction, 这里实现 BiFunction.apply(param1,param2) 接口即可。支持lambda表达式,形如:(result,item)->{...} 。
返回值:返回Optional对象,由于结果存在空指针的情况(当集合为空时)因此需要使用Optional。 `` public class LambdaTest { public static void main(String[] args) { List list=Lists.newArrayList(1,2,3,4,5); //将数组进行累加求和 //由于返回的是 Optional ,因此需要get()取出值。 Integer total=list.stream().reduce((result,item)->result+item).get(); System.out.println(total); } }
``
将累加的每一步打印,可以发现Lambda表达式中的两个参数(result,item)的含义:
第一个参数 result :初始值为集合中的第一个元素,后面为每次的累加计算结果 ;
第二个参数 item :遍历的集合中的每一个元素(从第二个元素开始,第一个被result使用了)。
- 通常于map搭配使用 map 提取需要统计的数据
- reduce聚合计算方法 进行统计
代码示例:
public class Lambda14 {
public static void main(String[] args) {
List<Student> students = Arrays.asList(new Student("张三", 18),
new Student("李四", 19),
new Student("王五", 21),
new Student("赵六", 22));
/**
* 内部类实现stream reduce
*/
Integer sumAge = students.stream().map(stu -> stu.getAge()).reduce(new BinaryOperator<Integer>() {
@Override
public Integer apply(Integer i1, Integer i2) {
System.out.println("i1:" + i1 + ",i2:" + i2);
return i1 + i2;
}
}).get();
System.out.println("内部类实现stream reduce");
System.out.println(sumAge);
/**
* Lambda实现stream reduce
*/
System.out.println("Lambda实现stream reduce");
Integer sumAgelambda = students.stream().map(Student::getAge).reduce((i1, i2) -> i1 + i2).get();
System.out.println(sumAgelambda);
}
}
class Student {
private String name;
private Integer age;
public Student(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
输出:
内部类实现stream reduce
i1:18,i2:19
i1:37,i2:21
i1:58,i2:22
80
Lambda实现stream reduce
80