The java8 stream reduce() method uses

The reduce() method may not be used much at ordinary times, because its common methods are encapsulated separately. For example sum(), max(), min(),count()都是通过reduce()操作的。

reduce() is the following three methods

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)

The main function is a single-parameter method. The following two ones increase the initial value of identity, and the other is to increase the operation of multi-segment values ​​during parallel processing.

Let's see an example:

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

The above output results:

6

A test of two parameters:

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

Output result: 

21

Let's look at three parameter examples:

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

Output result:

21

If parallel processing is not used, the method functions of three parameters and two parameters are exactly the same, and the subsequent processing of s1 and s2 does not play any role. After parallel processing is added, the result can handle multiple parallel processing. The result is processed again, here is another example:

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);

     process result:

720

Multiply multiple parallel processing results

Guess you like

Origin blog.csdn.net/caicai250/article/details/123551246