Purpose of third argument to 'reduce' function in Java 8 functional programming

前端 未结 3 1490
长情又很酷
长情又很酷 2020-12-02 20:27

Under what circumstances is the third argument to \'reduce\' called in Java 8 streams?

The code below attempts to traverse a list of strings and add up the code poin

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 21:19

    Are you talking about this function?

    reduce  U reduce(U identity,
                 BiFunction accumulator,
                 BinaryOperator combiner) 
    

    Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. This is equivalent to:

     U result = identity;
     for (T element : this stream)
         result = accumulator.apply(result, element)
     return result;   
    

    but is not constrained to execute sequentially. The identity value must be an identity for the combiner function. This means that for all u, combiner(identity, u) is equal to u. Additionally, the combiner function must be compatible with the accumulator function; for all u and t, the following must hold:

     combiner.apply(u, accumulator.apply(identity, t)) == 
         accumulator.apply(u, t)   
    

    This is a terminal operation.

    API Note: Many reductions using this form can be represented more simply by an explicit combination of map and reduce operations. The accumulator function acts as a fused mapper and accumulator, which can sometimes be more efficient than separate mapping and reduction, such as when knowing the previously reduced value allows you to avoid some computation. Type Parameters: U - The type of the result Parameters: identity - the identity value for the combiner function accumulator - an associative, non-interfering, stateless function for incorporating an additional element into a result combiner - an associative, non-interfering, stateless function for combining two values, which must be compatible with the accumulator function Returns: the result of the reduction See Also: reduce(BinaryOperator), reduce(Object, BinaryOperator)

    I assume its purpose is to allow parallel computation, and so my guess is that it's only used if the reduction is performed in parallel. If it's performed sequentially, there's no need to use combiner. I do not know this for sure -- I'm just guessing based on the doc comment "[...] is not constrained to execute sequentially" and the many other mentions of "parallel execution" in the comments.

提交回复
热议问题