Inconsistency in Java 8 method signatures

后端 未结 3 429
名媛妹妹
名媛妹妹 2021-02-08 09:46

Java 8 has given us new methods with really long signatures like this:

static > Collector toMap(
    Function&l         


        
3条回答
  •  离开以前
    2021-02-08 10:27

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

提交回复
热议问题