392

I have two sets, A and B, of the same type.

I have to find if A contains any element from the set B.

What would be the best way to do that without iterating over the sets? The Set library has contains(object) and containsAll(collection), but not containsAny(collection).

1
  • 4
    Are you trying to avoid iterating for efficiency reasons, or for code cleanliness?
    – yshavit
    Jan 3, 2012 at 6:19

9 Answers 9

657

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.

9
  • 20
    Prefer this to the other solutions because it does not modify either of the sets or creates a new one.
    – devconsole
    Sep 20, 2012 at 10:37
  • 7
    And is standard JRE, and works with any Collections, not just set. Jun 26, 2016 at 15:32
  • 5
    I don't think this is speediest, it won't short-circuit when the first element of the intersection is found.
    – Ben Horner
    Jul 14, 2016 at 4:16
  • 11
    Actually it will short-circuit as soon as it finds the first common element
    – Xipo
    Dec 15, 2016 at 10:54
  • 5
262

Stream::anyMatch

Since Java 8 you could use Stream::anyMatch.

setA.stream().anyMatch(setB::contains)
8
  • 3
    This is exactly what I was looking for! Thanks :-) I also didn't know you could use variables with the :: syntax!
    – dantiston
    Apr 15, 2016 at 23:15
  • 17
    @Cristiano here, anyMatch will stream all of the elements from setA and call setB.contains() on all of them. If "true" is returned for any of the elements, the expression as a whole will evaluate to true. Hope this helped.
    – Alex
    Jul 11, 2016 at 18:12
  • 2
  • 7
    This works, but it's inefficient if setA is large. The right answer is to call Collections.disjoint.
    – Doradus
    Sep 11, 2020 at 19:23
  • 3
    The efficiency of anyMatch is the same as efficiency of Collections.disjoint.
    – gpl
    Sep 21, 2020 at 13:29
56

Apache Commons has a method CollectionUtils.containsAny().

3
41

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.

4
  • 3
    The only disadvantage of using this approach is you have to include guava libraries. Which I think is not disadvantage because google collection APIs are very strong. Jan 11, 2014 at 15:27
  • @DidierL most of the Guava Collections utility functions, including this one, return views of the data structures. So there is no "building the set" to worry about in this case. The implementation is interesting to read here, and/or see the javadoc: google.github.io/guava/releases/21.0/api/docs/com/google/common/…
    – chut
    Sep 29, 2018 at 23:14
  • @MohammadAdnan Another disadvantage is that it computes the full intersection - if set1 and set2 are very large, this would be plenty more resource intensive (both CPU and memory wise) than just checking if they have any item in common.
    – Marxama
    Jun 9, 2020 at 9:08
  • 2
    @MohammadAdnan That is not the only disadvantage. In containsAny logic you should, if not must, return as soon as a match is found but this method will run until end-of-data reached in both sets
    – Farid
    May 21, 2021 at 18:42
29

I use org.apache.commons.collections.CollectionUtils

CollectionUtils.containsAny(someCollection1, someCollection2)

That is All! Returns true if at least one element is in both collections.

Simple to use, and the name of the function is more suggestive.

0
5

Use retainAll() in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.

3
  • If the point of avoiding the iteration is for efficiency, retainAll probably won't help. Its implementation in AbstractCollection iterates.
    – yshavit
    Jan 3, 2012 at 6:17
  • 2
    yshavit is correct. Given that the O.P. is looking to see if any element exists in both sets, a proper algorithm would have an O(1) running time in the best case, whereas retainAll would have something along the lines of an O(N) (it would depend on the size of only 1 set) best-case running time.
    – Zéychin
    Jan 3, 2012 at 6:27
  • retainAll is destructive. It removes non common elements from the original List or Set. It gets an issue if you are in a loop and need to preserve the initial collection.
    – Kir Kanos
    Sep 20, 2023 at 13:14
3

I would recommend creating a HashMap from set A, and then iterating through set B and checking if any element of B is in A. This would run in O(|A|+|B|) time (as there would be no collisions), whereas retainAll(Collection<?> c) must run in O(|A|*|B|) time.

3

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

2

You can use retainAll method and get the intersection of your two sets.

2
  • In most cases one needs to keep the original set, so in order to use retainAll it's necessary to make a copy of the original set. Then it's more efficient to use HashSet as suggested by Zéychin .
    – Petr
    Sep 7, 2012 at 14:54
  • That's a state change, not condition check
    – Ben
    May 3, 2020 at 0:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.