栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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 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!

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号