Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Java stream().noneMatch(...) and !stream().anyMatch(...) [duplicate]

Is there is any difference in performance or anything else if I do

  1. list.stream().noneMatch(...)
  2. !list.stream().anyMatch(...)
like image 949
FlashSloth Avatar asked Dec 22 '22 21:12

FlashSloth


1 Answers

Both noneMatch and anyMatch are short-circuiting stream operations. That means that they will stop processing their input when the result becomes known.

In your case, they will each stop when they do find a match to the Predicate that is passed in. The only difference is that noneMatch will return false on a match and anyMatch will return true. Your negating the result from anyMatch makes the two expressions logically equivalent.

Assuming the same list and the same Predicate, any performance difference would be negligible. Both methods will short-circuit on the first match, if any, working through the entire list if none actually match, and one negation operator won't make a difference either.

like image 179
rgettman Avatar answered Jan 07 '23 12:01

rgettman