Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8313436

Add Collections.containsAny(), containsNone(), allMatch(), anyMatch(), noneMatch()



    • Enhancement
    • Resolution: Won't Fix
    • P4
    • None
    • None
    • core-libs
    • None


      I'm filing this Enhancement to document the rationale for not providing these methods. The following questions come up from time to time:

      * The Collection interface has a containsAll() method. Shouldn't it also have containsAny() and containsNone() methods?

      * The Stream interface has terminal operations allMatch(), anyMatch(), and noneMatch(), all of which take a predicate. Wouldn't it be convenient to have these on the Collection interface too?

      The main reason to avoid adding too many methods to Collection is that it's a widely implemented interface, and adding methods runs the risk of creating conflicts with methods of existing implementations. See this message:


      (This message also explains the separation between eager/mutating operations on collections and lazy/non-mutating operations on streams, though these are somewhat smaller considerations for the methods discussed here, which don't mutate.)

      The putative Collection.containsX methods can easily be implemented using streams, at only a slight increase in verbosity:

      coll.containsAll(other) ~~ other.stream().allMatch(coll::contains)
      coll.containsAny(other) ~~ other.stream().anyMatch(coll::contains)
      coll.containsNone(other) ~~ other.stream().noneMatch(coll::contains)

      The stream xMatch methods are easily invoked by converting the collection to a stream by first calling stream().

      Adding these methods directly to Collection allows the possibility of overriding them, but the performance benefits of doing so are unclear. Adding the methods would add a little bit of convenience but it doesn't actually add much if any power to what we have with Collections+Streams today. The benefits don't seem to offset the compatibility risk.

      There's an argument to be made for EnumSet.containsAny() and possibly containsNone() if the argument is another EnumSet, as these can be implemented as fast bitwise operations that (for the most part) avoid iteration. See JDK-6767177.


        Issue Links



              smarks Stuart Marks
              smarks Stuart Marks
              0 Vote for this issue
              1 Start watching this issue