多个“匹配”检查一个流 [英] Multiple "match" checks in one stream
问题描述
是否可以检查数组(或集合)是否包含除5之外的元素5 和元素。在 one 流中返回布尔结果而不是使用两个流:
Is it possible to check if an array (or collection) contains element 5 and element other than 5. In one stream returning boolean result instead of using two streams:
int[] ints = new int[]{1, 2, 3, 4, 5};
boolean hasFive = IntStream.of(ints).anyMatch(num -> num == 5);
boolean hasNonFive = IntStream.of(ints).anyMatch(num -> num != 5);
boolean result = hasFive && hasNonFive;
推荐答案
在这种特殊情况下,即你想知道是否一个流或数组包含匹配和非匹配元素(一个匹配谓词否定的元素),你可以做得更简单。
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]);
这篇关于多个“匹配”检查一个流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!