4

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

  1. list.stream().noneMatch(...)
  2. !list.stream().anyMatch(...)
FlashSloth
  • 67
  • 1
  • 4
  • It depends on the likelihood and most notable on the different `...`s in your code. – U. Windl Sep 04 '19 at 00:18
  • @U.Windl since the OP obviously means the same `...` for both, it does not. – Holger Sep 04 '19 at 07: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 04 '19 at 07:48
  • @U.Windl read [the answer](https://stackoverflow.com/a/57779846/2711488). Both stop at the first match. The only difference is the opposite boolean result. – Holger Sep 04 '19 at 07:54
  • @Holger: If both constructs shall be equivalent the `...`s must be different. – U. Windl Sep 04 '19 at 10:59
  • @U.Windl there is a `!` (logical not) before the second construct. Assuming identical `...`, they *are* equivalent. – Holger Sep 04 '19 at 11:12

1 Answers1

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.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • 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 04 '19 at 08:07