java8 stream reduce()方法使用

reduce()这个方法可能平时用得不多,因为它的常用方法都被单独封装起来了。比如sum()max()min()count()都是通过reduce()操作的。

reduce()是下面三个方法

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

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

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

主要功能 是单参数方法的 ,下面两个一个增加初始值identity,一个是增加并行处理时,多段值的操作。

下面 看例子:

//找出最大数
        Optional<Integer> student = Stream.of(1, 2, 3, 4, 5, 6).reduce((v1, v2) -> v1 > v2 ? v1 : v2);
        System.out.println(student.get());

上面输出结果:

6

两个参数的测试:

//设置一个默认值,从默认值开始处理
        Integer result = Stream.of(1, 2, 3, 4, 5, 6).reduce(0, (v1, v2) -> v1 + v2);
        System.out.println(result);

输出结果: 

21

下面看三个参数例子:

Integer studentId = Stream.of(1, 2, 3, 4, 5, 6).reduce(0,
                (sum, v) -> {
                    return sum + v;
                },
                (s1, s2) -> s1 + s2);

输出结果:

21

如果在不使用并行处理的时候,三个参数跟两个参数的方法功能一模一样,而且后面s1跟s2的处理不起到 任何作用的,当加上并行处理 后,结果可以处理多个并行处理的结果再次 处理 ,下面再来个例子 :

Integer studentId = Stream.of(1, 2, 3, 4, 5, 6).parallel().reduce(0,
                (sum, v) -> {
                    return sum + v;
                },
                (s1, s2) -> s1 * s2);
        System.out.println(studentId);

     处理结果:

720

将 多个并行 处理结果相乘

猜你喜欢

转载自blog.csdn.net/caicai250/article/details/123551246
今日推荐