对于我的具体情况,我想在减少中使用功能组合;例如:
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 是这样设计的?ABinaryOperator
是 a ,所以用超类型BiFunction
声明方法的参数不是更有意义吗?reduce