如何在Stream上短路减少? [英] How to short-circuit reduce on Stream?
问题描述
假设我有一个布尔值流,我正在写的reduce操作是 ||
(OR)。如果遇到 true
值,是否可以放弃至少部分元素的评估?
Suppose I have a stream of boolean values and the reduce operation that I am writing is ||
(OR). Can I write it in a way such that the evaluation of at least some of the elements is abandoned if a true
value is encountered?
我正在寻找一些优化(可能是一个并行流),不一定是完全优化,虽然后者会很棒。
I am looking for some amount of optimization (perhaps if it is a parallel stream), not necessarily full optimization although the latter would be awesome.
推荐答案
我怀疑你想要这种类型的构造。
I suspect you want this type of construct.
// stop when any element evaluates to true
boolean any = stream.anyMatch(t -> t);
你可以用peek检查这个
You can check this with peek
Stream.of(1, 2, 3, 4).peek(System.out::println).anyMatch(i -> i == 2);
打印
1
2
对于并行示例
AtomicInteger count = new AtomicInteger();
IntStream.range(0, 1000).parallel().peek(t -> count.incrementAndGet()).anyMatch(i -> i == 2);
System.out.println("count: " + count);
打印一个数字,如
count: 223
具体数字各不相同。
对于referencePipeline, anyMatch
调用
For a referencePipeline, the anyMatch
calls
@Override
public final boolean anyMatch(Predicate<? super P_OUT> predicate) {
return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.ANY));
}
调用此
public static <T> TerminalOp<T, Boolean> makeRef(Predicate<? super T> predicate,
MatchKind matchKind) {
Objects.requireNonNull(predicate);
Objects.requireNonNull(matchKind);
class MatchSink extends BooleanTerminalSink<T> {
MatchSink() {
super(matchKind);
}
@Override
public void accept(T t) {
if (!stop && predicate.test(t) == matchKind.stopOnPredicateMatches) {
stop = true;
value = matchKind.shortCircuitResult;
}
}
}
return new MatchOp<>(StreamShape.REFERENCE, matchKind, MatchSink::new);
}
您可以在这里看到短路代码。
where you can start to see the short circuiting code.
这篇关于如何在Stream上短路减少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!