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

后端 未结 2 1278
一向
一向 2021-01-12 11:05

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 wil

相关标签:
2条回答
  • 2021-01-12 11:50

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

    0 讨论(0)
  • 2021-01-12 11:51

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

    • Easy of use.
    • Clarity of purpose.
    0 讨论(0)
提交回复
热议问题