代码之家  ›  专栏  ›  技术社区  ›  Mahozad

java集的并集与交集

  •  2
  • Mahozad  · 技术社区  · 7 年前

    最简单的方法是什么? Set 在爪哇?我看到了这个简单问题的一些奇怪的解决方案(例如手动迭代这两个集合)。

    enter image description here enter image description here

    3 回复  |  直到 6 年前
        1
  •  11
  •   Mahozad    6 年前

    最简单的单行解决方案是:

    set1.addAll(set2); // Union
    
    set1.retainAll(set2); // Intersection
    

    上述解决方案是 破坏性的 意思是原文的内容 集合1 我的零钱。如果不想触摸现有的集,请创建一个新集:

    Set<E> result = new HashSet<>(set1);
     // └─ your specific type
    
    result.addAll(set2); // Union
    
    result.retainAll(set2); // Intersection
    
        2
  •  3
  •   Nitin Bisht    7 年前

    你可以通过使用 Google's Guava library 是的。下面以一个例子说明:

        // Set a
        Set<String> a = new HashSet<String>();
        a.add("x");
        a.add("y");
        a.add("z");
    
        // Set b
        Set<String> b = new HashSet<String>();
        b.add("x");
        b.add("p");
        b.add("q");
    

    现在,用java计算两个集合的交集:

    Set<String> intersection = Sets.intersection(a, b);
    System.out.printf("Intersection of two Set %s and %s in Java is %s %n",
                    a.toString(), b.toString(), intersection.toString());
    

    输出: Intersection of two Set [z, y, x] and [q, p, x] in Java is [x]

    类似地,在Java中计算两个集合的并集:

    Set<String> union = Sets.union(a, b);
    System.out.printf("Union of two Set %s and %s in Java is %s %n",
                    a.toString(), b.toString(), union.toString());
    

    输出: Union of two Set [z, y, x] and [q, p, x] in Java is [q, p, x, z, y]

    你可以在 https://google.github.io/guava/releases/18.0/api/docs/

    为了将番石榴库添加到项目中,您可以看到 https://stackoverflow.com/a/4648947/8258942

        3
  •  3
  •   David Lilljegren    6 年前

    虽然番石榴确实更整洁,也几乎是标准的,但这里有一种非破坏性的方法,只使用标准java来实现联合和交叉。

    Set s1 = Set.of(1,2,3);
    Set s2 = Set.of(3,4,5);     
    
    Set union = Stream.concat(s1.stream(),s2.stream()).toSet(); 
    Set intersect = s1.stream().filter(s2::contains).toSet();
    
    推荐文章