java8 srteam接口终端操作reduce操作

对于中间操作和终端操作的定义,请看《JAVA8 stream接口 中间操作和终端操作》,这篇主要讲述的是stream的reduce操作,

reduce 是一种归约操作,将流归约成一个值的操作叫做归约操作,用函数式编程语言的术语来说,这种称为折叠(fold);

我们先看下函数的定义

T reduce(T identity, BinaryOperator<T> accumulator);
 
	Optional<T> reduce(BinaryOperator<T> accumulator);
 
	<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);

接口对应的实现如下:

@Override
    public final P_OUT reduce(final P_OUT identity, final BinaryOperator<P_OUT> accumulator) {
        return evaluate(ReduceOps.makeRef(identity, accumulator, accumulator));
    }

    @Override
    public final Optional<P_OUT> reduce(BinaryOperator<P_OUT> accumulator) {
        return evaluate(ReduceOps.makeRef(accumulator));
    }

    @Override
    public final <R> R reduce(R identity, BiFunction<R, ? super P_OUT, R> accumulator, BinaryOperator<R> combiner) {
        return evaluate(ReduceOps.makeRef(identity, accumulator, combiner));
    }

可以看到,第一个和第三个,是一个重载方法,调用的同一个实现;下面,我们看下具体的小案例

 List<Integer> numbers = Stream.iterate(1, x -> x + 1).limit(10).collect(Collectors.toList());
        Integer aa = 0;
        for (Integer i : numbers) {
            aa += i;
        }
        Integer dd = numbers.stream().reduce(0, (a, b) -> a + b, (a, b) -> a - b);
        Optional<Integer> dd1 = numbers.stream().reduce((a, b) -> a + b);
        System.out.println(aa);
        System.out.println(dd);
        System.out.println(dd1.get());

我们使用无限流,生成了1-10的数字的list,关于无限流的解释,以及流的创建的方式,可以 参看《java8 Stream-创建流的几种方式》

在java8之前,我们对数据求和的,是需要对list进行遍历,然后累加求和的;在案例中,变量aa就是对list遍历累加求和的出处理;从第二段代码中开始,就是java8中的求和方式

T reduce(T identity, BinaryOperator<T> accumulator);

这个函数,接受2个参数,第一个表示初始值,第二个值,传入的是一个函数式接口BinaryOperator,这个接口继承BiFunction;计算的表达式的规则;

Optional<T> reduce(BinaryOperator<T> accumulator);

这个接口。只用传入计算规则,初始值是list的第一个参数,返回的optional对象,预防list里,全部是null;

<U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner);
关于这个三个参数的接口,在《java8实战》这本书中,没有做介绍。我也不是特别理解,查阅过一些资料,在多线程中使用的,具体感兴趣的,可以参考 《 java8中3个参数的reduce方法怎么理解?》



猜你喜欢

转载自blog.csdn.net/qq_28410283/article/details/80873910