Something like 'contains any' for Java set?

前端 未结 9 744
余生分开走
余生分开走 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.

提交回复
热议问题