Java – how to reduce short circuit on stream?

Suppose I have a Boolean stream and the reduce operation I write is 𞓜 (or) Can I write in such a way that if I encounter a real value, at least some elements are abandoned?

I'm looking for some optimizations (maybe if it's a parallel stream), not necessarily complete optimizations, although the latter will be awesome

Solution

I doubt you want this type of structure

// stop when any element evaluates to true
boolean any = stream.anyMatch(t -> t);

You can check it carefully

Stream.of(1,2,3,4).peek(System.out::println).anyMatch(i -> i == 2);

print

1
2

For a parallel example

AtomicInteger count = new AtomicInteger();
IntStream.range(0,1000).parallel().peek(t -> count.incrementAndGet()).anyMatch(i -> i == 2);
System.out.println("count: " + count);

Print a number

count: 223

The exact figures vary

For referencepipeline, anymatch is called

@Override
public final boolean anyMatch(Predicate<? super P_OUT> predicate) {
    return evaluate(MatchOps.makeRef(predicate,MatchOps.MatchKind.ANY));
}

This is called

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

There you can see the short circuit code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>