【问题标题】:Intersection of two sets [duplicate]两组的交集[重复]
【发布时间】:2015-07-14 09:05:33
【问题描述】:

获得两组交集的简单方法是什么? 我有:

    Set<Long> set1 = {1,2,3}
    Set<Long> set2 = {2,3,4}

我看起来或方法如下:

    Set<Long> intersection = new HashSet<>();
    intersection.intersect(set1, set2);

而intersection.toString() 产生我的集合包含{2,3}

【问题讨论】:

标签: java set


【解决方案1】:

您可以使用retainAll()

请注意,这将修改其中一个集合,因此您可能需要先创建一个副本。

【讨论】:

    【解决方案2】:

    使用SetretainAll()方法

    Set<String> s1;
    Set<String> s2;
    s1.retainAll(s2); // s1 now contains only elements in both sets
    

    但是,retainAll,会修改s1的内容。您应该创建一个s1 的副本并在该副本上使用retainAll

    通过下面避免这种情况,

    Set<String> mySet = new HashSet<String>(s1); // use the copy constructor
    mySet.retainAll(s2);
    

    【讨论】:

      【解决方案3】:

      retainAll() 方法用于从列表中删除不包含在指定集合中的元素。

      Set<Long> set1 = {1,2,3}
      Set<Long> set2 = {2,3,4}    
      set1.retainAll(set2);//finally prints 2,3
      

      【讨论】:

        【解决方案4】:

        或保留值:

        Set<String> intersection = new HashSet<String>(set1);
        intersection.retainAll(set2);
        

        【讨论】:

          猜你喜欢
          • 2017-01-04
          • 1970-01-01
          • 2013-04-20
          • 2012-05-12
          • 2015-12-23
          • 1970-01-01
          • 2018-06-11
          • 2011-12-13
          • 2011-12-23
          相关资源
          最近更新 更多