这是涉及我的两个解决方案StreamEx https://github.com/amaembo/streamex图书馆。我在这里使用的核心功能是短路集电极的概念。我的图书馆增强了Collector
提供短路能力的概念(适用于顺序流和并行流)
如果谓词与您的示例中类似(一个与另一个相反),您可以使用partitioningBy
:
Map<Boolean, Optional<Integer>> map = IntStreamEx.of(ints).boxed()
.partitioningBy(num -> num == 5, MoreCollectors.first());
现在您应该检查这两个映射是否都存在:
System.out.println(map.values().stream().allMatch(Optional::isPresent));
或者在单个语句中:
System.out.println(IntStreamEx.of(ints).boxed()
.partitioningBy(num -> num == 5, MoreCollectors.first())
.values().stream().allMatch(Optional::isPresent));
这里我们使用的是MoreCollectors.first() http://amaembo.github.io/streamex/javadoc/one/util/streamex/MoreCollectors.html#first--集电极短路。该解决方案与@user140547提出的解决方案类似,但一旦找到两个元素,它实际上就会停止处理。
对于两个自定义谓词,可以使用pairing http://amaembo.github.io/streamex/javadoc/one/util/streamex/MoreCollectors.html#pairing-java.util.stream.Collector-java.util.stream.Collector-java.util.function.BiFunction-集电极,它结合了两个集电极的结果(如果输入集电极短路,则保留短路)。但首先,我们需要anyMatching
收集器(我的图书馆中没有):
import static one.util.streamex.MoreCollectors.*;
static <T> Collector<T, ?, Boolean> anyMatching(Predicate<T> pred) {
return collectingAndThen(filtering(pred, first()), Optional::isPresent);
}
Collector<Integer, ?, Boolean> hasFive = anyMatching(num -> num == 5);
Collector<Integer, ?, Boolean> hasNonFive = anyMatching(num -> num != 5);
Collector<Integer, ?, Boolean> hasBoth = pairing(hasFive, hasNonFive,
(res1, res2) -> res1 && res2);
System.out.println(IntStreamEx.of(ints).boxed().collect(hasBoth));