Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream - purpose of having both anyMatch and noneMatch operations?

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.

like image 764
Tranquility Avatar asked Jan 29 '16 19:01

Tranquility


People also ask

What is the use of anyMatch () function in stream?

anyMatch() It returns whether any elements of this stream match the provided predicate. It may not evaluate the predicate on all elements if not necessary for determining the result.

What is the difference between the anyMatch () and findAny () stream methods?

Stream#anyMatch() returns a boolean while Stream#findAny() returns an object which matches the predicate. They almost do the same work. anyMatch is a short-circuit operation, but filter will always process the whole stream.

What is the difference between allMatch and anyMatch?

anyMatch() returns true if any of the elements in a stream matches the given predicate. If the stream is empty or if there's no matching element, it returns false . allMatch() returns true only if ALL elements in the stream match the given predicate.

What is true of the noneMatch () function in stream?

The noneMatch() returns: true – if no element in the stream matches the given predicate, or the stream is empty.


2 Answers

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

  • Easy of use.
  • Clarity of purpose.
like image 58
Andreas Avatar answered Oct 17 '22 03:10

Andreas


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.)

like image 42
Louis Wasserman Avatar answered Oct 17 '22 01:10

Louis Wasserman