Java 8 has given us new methods with really long signatures like this:
static > Collector toMap(
Function&l
You are right in that the functional signature of the merge operation (the same applies to reduce) does not require an interface like BinaryOperator
.
This can not only be illustrated by the fact that the mergeFunction
of the toMap
collector will end up at Map.merge which accepts a BiFunction super V,? super V,? extends V>
; you can also convert such a BiFunction
to the required BinaryOperator
:
BiFunction
MULTIPLY_DOUBLES = (a, b) -> a.doubleValue() * b.doubleValue();
Stream s = Stream.of(42.0, 0.815);
Optional n=s.reduce(MULTIPLY_DOUBLES::apply);
or full generic:
public static Optional reduce(
Stream s, BiFunction super T, ? super T, ? extends T> f) {
return s.reduce(f::apply);
}
The most likely reason for creating BinaryOperator
and UnaryOperator
is to have symmetry with the primitive type versions of these functions which don’t have such a super interface.
In this regard, the methods are consistent
Stream.reduce(BinaryOperator)
IntStream.reduce(IntBinaryOperator)
DoubleStream.reduce(DoubleBinaryOperator)
LongStream.reduce(LongBinaryOperator)
or
Arrays.parallelPrefix(T[] array, BinaryOperator op)
Arrays.parallelPrefix(int[] array, IntBinaryOperator op)
Arrays.parallelPrefix(double[] array, DoubleBinaryOperator op)
Arrays.parallelPrefix(long[] array, LongBinaryOperator op)