🍰 个人主页:_小白不加班__
🍞文章有不合理的地方请各位大佬指正。
🍉文章不定期持续更新,如果我的文章对你有帮助➡️ 关注🙏🏻 点赞👍 收藏⭐️
文章目录
- 常见场景图示
- `reduce`中的`BiFunction`和`BinaryOperator`是什么
- 理解`reduce`
- T reduce(T identity, BinaryOperator<T> accumulator);
- Optional<T> reduce(BinaryOperator<T> accumulator);
 
- 代码举例
 
常见场景图示
我们常见使用场景:累加、求最大值 如图示
 累加:
求最大值:
reduce中的BiFunction和BinaryOperator是什么
 
reduce定义如下:
  T reduce(T identity, BinaryOperator<T> accumulator);
首先了解一下BiFunction和BinaryOperator
 带有Binary和Bi关键字都是二元运算(就是谓词带有 有两个形参)
 
 BiFunction函数式接口如下:
 传入 T类型变量t U类型变量u 返回R类型变量
@FunctionalInterface
// (T t,U u)->R
public interface BiFunction<T, U, R> {
    R apply(T t, U u);
}
BinaryOperator函数式接口如下:
 继承BiFunction 形参类型和返回类型相同
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
    
}
理解reduce
 
reduce常见的定义方式:
 T reduce(T identity, BinaryOperator accumulator);
 Optional<T> reduce(BinaryOperator<T> accumulator);
下面详细解释
T reduce(T identity, BinaryOperator accumulator);
第一个参数传入T类型值,第二分谓词 (T t,T t)->T 返回值类型为T
通俗点总结:
 一个初始值
 一个Lambda来把两个流元素结合起来并产生一个新值
 常用:累加、累积
Optional reduce(BinaryOperator accumulator);
谓词 (T t,T t)->T 返回值类型为T
Optional容器类表示一个值存在或者不存在,避免和null检查
reduce要考虑新的值和下一个元素,将流中的第一个元素作为初始值,比较产生最大值,然后继续和下一个元素比较。
 常用:最大值,最小值
代码举例
最开始的图示的代码如下:
 累加:
List<Integer> integers = Arrays.asList(4, 5, 3, 9);
Integer reduce = integers.stream().reduce(0, (a, b) -> a + b);
System.out.println("求和:"+reduce);
//求和:21

 求最大值:
List<Integer> integers = Arrays.asList(4, 5, 3, 9);
Optional<Integer> reduce = integers.stream().reduce(Integer::max);
System.out.println("最大值:" + reduce.get());
//最大值:9

 Optional的详细使用改天再更,关注不错过~~~~
🍉文章不定期持续更新,如果我的文章对你有帮助 ➡️ 关注 👍点赞 ⭐️收藏
🙏🏻 你们的支持是我 更新的动力


















