4

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

  1. list.stream().noneMatch(...)
  2. !list.stream().anyMatch(...)
6
  • It depends on the likelihood and most notable on the different ...s in your code.
    – U. Windl
    Sep 4, 2019 at 0:18
  • @U.Windl since the OP obviously means the same ... for both, it does not.
    – Holger
    Sep 4, 2019 at 7:38
  • @Holger: noneMatch() most likely ends after having examined all the elements, while anyMatch() can end after having found the first match.
    – U. Windl
    Sep 4, 2019 at 7:48
  • @U.Windl read the answer. Both stop at the first match. The only difference is the opposite boolean result.
    – Holger
    Sep 4, 2019 at 7:54
  • @Holger: If both constructs shall be equivalent the ...s must be different.
    – U. Windl
    Sep 4, 2019 at 10:59

1 Answer 1

12

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.

1
  • 1
    …and those who are still not convinced, may try System.out.println(IntStream.range(0,1_000).peek(System.out::println).noneMatch(i-> i==5)); System.out.println(IntStream.range(0,1_000).peek(System.out::println).anyMatch(i-> i==5));
    – Holger
    Sep 4, 2019 at 8:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.