为什么java.util.stream.Stream.reduce`使用`BinaryOperator `而不是`BiFunction `?

问题描述 投票:1回答:1

对于我的具体情况,我想简化使用功能组合。

例如:

    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, Sets.SetView<Integer>> f = Sets::intersection;
    Function<Sets.SetView<Integer>, ImmutableSet<Integer>> g = Sets.SetView::immutableCopy;
    BiFunction<ImmutableSet<Integer>, ImmutableSet<Integer>, ImmutableSet<Integer>> biFunction = f.andThen(g);
    ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
        .reduce(biFunction)
        .orElse(ImmutableSet.of());

获取编译错误:

argument mismatch BiFunction cannot be converted to BinaryOperator

相反,我需要这样做:

    ImmutableSet<Integer> intersection = Stream.of(ImmutableSet.of(1, 2, 3), ImmutableSet.of(1, 2), ImmutableSet.of(4))
        .reduce((a, b) -> Sets.intersection(a, b).immutableCopy())
        .orElse(ImmutableSet.of());

但是这失去了合成提供的无意义样式。

我的问题是,为什么Stream API如此设计。 BinaryOperator是BiFunction,所以用超类型声明方法不是更有意义吗?

java-8 java-stream
1个回答
0
投票
reduce操作必须采用相同类型的参数并返回相同类型。如果没有,则类型不匹配。这就是BanaryOperator的确切含义:BinaryOperator<T> extends BiFunction<T,T,T>
© www.soinside.com 2019 - 2024. All rights reserved.