Something like 'contains any' for Java set?

前端 未结 9 673
余生分开走
余生分开走 2020-11-28 01:52

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

相关标签:
9条回答
  • 2020-11-28 02:29

    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.

    0 讨论(0)
  • 2020-11-28 02:31

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

    0 讨论(0)
  • 2020-11-28 02:34

    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 讨论(0)
  • 2020-11-28 02:35

    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

    0 讨论(0)
  • 2020-11-28 02:37

    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.

    0 讨论(0)
  • 2020-11-28 02:43

    Apache Commons has a method CollectionUtils.containsAny().

    0 讨论(0)
提交回复
热议问题