Java – the strange “reduce” method group is in the jdk8 batch collection operation library

Why does the new jdk8 stream class only contain the following reduce methods:

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

However, it is not an obvious method. Corresponding to the reduction / folding function found in other languages (e.g. Haskell foldl:: (a – > b – > A) – > a – > [b] – a), it may look like this:

U reduce(U identity,U> reducer)

Instead, there is a similar method that has an additional combiner parameter I don't even know how to use it, because I link to the API document above. In the example, I don't use this parameter, it only refers to its required properties

Why does the jdk8 method do this? How can I imitate the standard folding behavior?

Solution

Parallel operations like reduced data act as general value aggregation operations on data sets, such as element arrays You can use them to implement, for example, summation

The order in which the values of the dataset are grouped together (such as summation) is not specified, so they do not correspond to the reduceleft / foldleft found in foldl found in Haskell or Scala

When the aggregate result type is different from the element type, the additional combiner parameter in the third line is used In these cases, you must specify how to combine the two results Let's say you want to use the third reduce to implement the number of vowels in the string The data element is a character. Reducer specifies the combination of the character and the current count:

(Integer count,Character c) -> if (isVowel(c)) count + 1 else count

The combiner is just a sum:

(Integer count1,Integer count2) -> count1 + count2

For example, Scala parallel collections have these for a while now

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>