Something like 'contains any' for Java set?

Stream::anyMatch

Since Java 8 you could use Stream::anyMatch.

setA.stream().anyMatch(setB::contains)

Wouldn't Collections.disjoint(A, B) work? From the documentation:

Returns true if the two specified collections have no elements in common.

Thus, the method returns false if the collections contains any common elements.


A good way to implement containsAny for sets is using the Guava Sets.intersection().

containsAny would return a boolean, so the call looks like:

Sets.intersection(set1, set2).isEmpty()

This returns true iff the sets are disjoint, otherwise false. The time complexity of this is likely slightly better than retainAll because you dont have to do any cloning to avoid modifying your original set.


Apache Commons has a method CollectionUtils.containsAny().

Tags:

Java