6

Why is the accumulator argument in the Stream::reduce method a BiFunction and not a BinaryOperator like the combiner argument.

Why is its type BiFunction<U, ? super T, U>? Why T? Should it be BiFunction<U, ? extends U, U>?

Eran
  • 387,369
  • 54
  • 702
  • 768
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
  • 2
    The question is not entirely clear, but it *might* be related to http://stackoverflow.com/questions/35680706/what-are-good-reasons-for-choosing-invariance-in-an-api-like-stream-reduce (although it rather seems to be the "opposite" question...) – Marco13 Dec 08 '16 at 09:57
  • Does this answer your question? [Why is a combiner needed for reduce method that converts type in java 8](https://stackoverflow.com/questions/24308146/why-is-a-combiner-needed-for-reduce-method-that-converts-type-in-java-8) – Jason Law Feb 01 '20 at 02:00

1 Answers1

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

The accumulator is a function that adds an element of the Stream (whose type is denoted by T) to the intermediate result of the reduce operation (whose type is denoted by U) and returns an updated result (also of type U).

Therefore you can't define it as a BinaryOperator, where the operands and result are all of the same type.

For example, you might pass as the accumulator in a reduce call a BiFunction<Integer,String,Integer> which is applied on a Stream<String> and produces the sum of the lengths of all the elements. You can't use a BinaryOperator<Integer> or a BinaryOperator<String> for that.

On the other hand, the combiner takes two intermediate results (both of the same type U) and merges them into a result whose type is also U. Therefore a BinaryOperator<U> (which extends BiFunction<U,U,U>) can be used.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • U reduce(U identity, BiFunction accumulator, BinaryOperator combiner); , i am asking about this version of the method the accumulator is BiFunction and the signature should be ? super U. https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html – 0xh3xa Dec 08 '16 at 09:39
  • 2
    @AhmadMoawad That's the same method signature I was referring to in my answer. – Eran Dec 08 '16 at 09:42