Something like 'contains any' for Java set?

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

提交回复
热议问题