1.方法介绍
【方法签名】
1.Optional<T> reduce(BinaryOperator<T> accumulator);【推荐使用】
*2.T reduce(T identity, BinaryOperator<T> accumulator);【重点理解这个】
3.<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
【太复杂且涉及高并发的处理,不建议使用】
【方法属性】终结方法
【方法参数】
重点介绍一下 T reduce(T identity, BinaryOperator<T> accumulator);
T identity : 给定的初始值;
BinaryOperator<T> accumulator : 自定义的处理逻辑,可以直接是一个Lambda表达式,
【方法作用】处理Stream中的元素,将多个元素“规约”为一个元素输出
2.案例代码
【注】:此案例代码都是采用了
串行流
的方式,并行流不考虑。
2.1 代码
package com.northcastle.I_stream;
import java.util.Optional;
import java.util.stream.Stream;
public class StreamTest12Reduce {
public static void main(String[] args) {
//0.准备一个数组
String[] strs = {"1","5","2","3","100"};
//1.把数组中的数据求和称为一个数据返回,不指定初始值
Optional<Integer> reduce1 = Stream.of(strs)
.map(Integer::parseInt)
.reduce((x, y) -> {
System.out.println("x = " + x + " ; y = " + y);
return x + y;
});
System.out.println("求和结果是 : "+reduce1.get());
System.out.println("=================================");
//2.把数组中的数据求和称为一个数据返回 : 指定初始值 为 0
Integer reduce2 = Stream.of(strs)
.map(Integer::parseInt)
.reduce(0, (x, y) -> {
System.out.println("x = "+x+" ; y = "+y);
return x+y;
});
System.out.println("求和结果是 : "+reduce2);
System.out.println("=================================");
//求最大值 : 模拟 max() 方法的实现逻辑
Optional<Integer> max = Stream.of(strs)
.map(Integer::parseInt)
.reduce((x, y) -> {
System.out.println("x = " + x + " ; y = " + y);
return x > y ? x : y; // 返回一个较大的值
});
System.out.println("最大值是 : "+max.get());
System.out.println("==================================");
}
}
2.2 执行结果
3.完成
Congratulations!
You are one step closer to success!