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

本文介绍了Java Stream API中的reduce方法,包括其不同重载形式和参数含义。通过案例代码展示了如何使用reduce进行数据求和、求最大值等操作,强调了指定初始值的重要性。同时,文中提醒在并行流情况下避免使用复杂reduce操作。
摘要由CSDN通过智能技术生成

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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值