且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多个“匹配”检查一个流

更新时间:2022-12-09 08:25:54

在这种特殊情况下,即你想知道是否一个流或数组包含匹配和非匹配元素(一个匹配谓词否定的元素),你可以做得更简单。

In this specific case, i.e. you want to know whether a stream or array contains both, a matching and a nonmatching element (an element matching the predicate’s negation), you can do it much simpler.

首先,测试是否第一个元素匹配谓词或其否定,然后,搜索流是否包含相反的任何匹配:

First, test whether the first element matches the predicate or its negation, then, search whether the stream contains any match of the opposite:

IntPredicate predicate=i -> i==5;

if(ints.length>0 && predicate.test(ints[0]))
    predicate=predicate.negate();
boolean result = IntStream.of(ints).anyMatch(predicate);

就是这样。如果您没有数组或集合作为流源,而是任意流,则测试第一个元素有点棘手:

That’s it. In case you don’t have an array or collection as the stream source, but an arbitrary stream, testing the first element is a bit trickier:

IntPredicate[] tmp={ null };
Spliterator.OfInt sp=intStream.spliterator();
boolean result = sp.tryAdvance(
    (int i) -> tmp[0]=predicate.test(i)? predicate.negate(): predicate)
 && StreamSupport.intStream(sp, false).anyMatch(tmp[0]);