reduce(T iden, BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。 返回 T
reduce(BinaryOperator b) 可以将流中元素反复结合起来,得到一个值。
返回 Optional<T>
备注:map 和 reduce 的连接通常称为map-reduce 模式,因 Google 用它
来进行网络搜索而出名。
代码展示
package com.csdn.test;
import com.csdn.entity.Employee;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* @author summer
* @date 2022-04-17 8:09
*/
public class TestFinal2 {
List<Employee> employees = Arrays.asList(
new Employee("张三",18,6666.66),
new Employee("李四",38,3333.66),
new Employee("王五",32,4444.66),
new Employee("赵六",42,5555.66),
new Employee("田七",21,9999.66),
new Employee("王八",19,8888.66),
new Employee("王八",19,8888.66),
new Employee("王八",19,8888.66),
new Employee("张九",52,7777.66)
);
@Test
public void test1(){
//求List中的和
List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
Integer reduce = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(reduce);
// 求employees集合中工资的总和
Double reduce1 = employees.stream().map(Employee::getSalary).reduce(0.0, (x, y) -> x + y);
System.out.println(reduce1);
Optional<Integer> reduce2 = list.stream().reduce((a, b) -> a + b);
System.out.println(reduce2.get());
}
}