I came across this code snippet:
List<String> colors = Arrays.asList("red", "green", "yellow");
Predicate<String> test = n ->
{
System.out.println("Searching…");
return n.contains("red");
};
colors.stream().filter(c -> c.length() > 3).allMatch(test);
The output showed me
Searching...
And when I take the .filter(c -> c.length() > 3)
away, it showed me
Searching...
Searching...
And after some other tests I found out that the last element (yellow) was never tested!
Why is that!?
Could somebody please be so kind and explain the mechanic behind it!?
Much appreciated!!!
You called allMatch
. This just wants to know "does every item match this predicate?". This will go through the stream and evaluate the predicate for each item until it finds one that is false, because once it has that, it can say for certain that not every item matches the predicate.
The docs say
May not evaluate the predicate on all elements if not necessary for determining the result.
Once it finds an item for which the predicate is false, it does not evaluate any further items.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.