10

The anyMatch operation will return true if it finds an element - the noneMatch operation will return false it if finds a matching element.

The anyMatch operation will return false if it finds no matching element - the noneMatch operation will return true if finds no matching element.

Therefore, instead of having both of these operations, could we not just do with one, or am I missing something? In essence, anyMatch returning false is a way of evaluating the truth of noneMatch's predicate.

djechlin
  • 59,258
  • 35
  • 162
  • 290
Tranquility
  • 3,061
  • 5
  • 23
  • 37
  • 1
    Try analyzing the results of those methods on an empty stream – Ferrybig Jan 29 '16 at 19:29
  • 2
    @Ferrybig: anyMatch returns false on an empty stream, noneMatch returns true on an empty stream. So OP's observation holds for an empty stream. – user140547 Jan 29 '16 at 20:20

2 Answers2

16

Same reason you have a != b, instead of only supporting ! (a == b):

  • Easy of use.
  • Clarity of purpose.
Andreas
  • 154,647
  • 11
  • 152
  • 247
12

Yes, we totally could. There's at least a moderately reasonable reason for it, though: the ! would go at the very beginning of a stream expression that could be chained many lines long, e.g. you'd have to write

 !collection.stream()
    .map(someMapFunction)
    .filter(someFilterFunction)
    .distinct()
    .sorted(myComparator)
    .map(someOtherMapFunction)
    .filter(someOtherFilterFunction)
    .anyMatch(somePredicate)

...and by the time you've reached the anyMatch when you're reading the code, the negation at the beginning is harder to remember.

(For what it's worth, the JDK generally seems to have a lot fewer redundant methods than other languages I could name.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413