Java8新特性 - Stream - 14 - Stream的reduce()规约方法详解

1.方法介绍

【方法签名】
		1.Optional reduce(BinaryOperator accumulator);【推荐使用】
		*2.T reduce(T identity, BinaryOperator accumulator);【重点理解这个】
		3. U reduce(U identity, BiFunction accumulator, BinaryOperator combiner);
		  【太复杂且涉及高并发的处理,不建议使用】
【方法属性】终结方法
【方法参数】
		重点介绍一下 T reduce(T identity, BinaryOperator accumulator);
		T identity : 给定的初始值;
		BinaryOperator 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 执行结果

Java8新特性 - Stream - 14 - Stream的reduce()规约方法详解_第1张图片

3.完成

Congratulations!
You are one step closer to success!

你可能感兴趣的:(JAVA基础篇,java8,Stream,reduce方法)