Something like 'contains any' for Java set?

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

    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.

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

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

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

    Stream::anyMatch

    Since Java 8 you could use Stream::anyMatch.

    setA.stream().anyMatch(setB::contains)
    
    0 讨论(0)
提交回复
热议问题