繁体   English   中英

Java中两组的对称差异

[英]Symmetric difference of two sets in Java

我的应用程序中有两个TreeSet

set1 = {501,502,503,504}
set2 = {502,503,504,505}

我想获得这些集的对称差异 ,以便我的输出将是集合:

set = {501,505}

你是在对称差异之后 这在Java教程中讨论。

Set<Type> symmetricDiff = new HashSet<Type>(set1);
symmetricDiff.addAll(set2);
// symmetricDiff now contains the union
Set<Type> tmp = new HashSet<Type>(set1);
tmp.retainAll(set2);
// tmp now contains the intersection
symmetricDiff.removeAll(tmp);
// union minus intersection equals symmetric-difference

您可以使用CollectionUtils#disjunction

编辑:

或者使用较少的Java-5之前的版本,使用Guava Sets#symmetricDifference

那些寻找set减法/补语 (非对称差异/分离)的人可以使用CollectionUtils.subtract(a,b)Sets.difference(a,b)

使用保留所有,删除所有然后addAll来做现有集合的联合。

  1. intersectionSet.retainAll(set2)// intersectionSet是set1的副本
  2. set1.addAll(SET2); //做一个set1和set2的联合
  3. 然后删除重复项set1.removeAll(intersectionSet);

您可以尝试从Eclipse Collections中设置 Sets.symmetricDifference()

Set<Integer> set1 = new TreeSet<>(Arrays.asList(501,502,503,504));
Set<Integer> set2 = new TreeSet<>(Arrays.asList(502,503,504,505));
Set<Integer> symmetricDifference =
        Sets.symmetricDifference(set1, set2);

Assert.assertEquals(
        new TreeSet<>(Arrays.asList(501, 505)),
        symmetricDifference);

注意:我是Eclipse Collections的提交者。

如果我们使用com.google.common.collect包,我们可能会发现这样的对称差异:

    Set<Integer> s1 = Stream.of( 1,2,3,4,5 ).collect( Collectors.toSet());
    Set<Integer> s2 = Stream.of( 2,3,4 ).collect( Collectors.toSet());
    System.err.println(Sets.symmetricDifference( s1,s2 ));

输出将是:[1,5]

Set<String> s1 = new HashSet<String>();
    Set<String> s2 = new HashSet<String>();
    s1.add("a");
    s1.add("b");
    s2.add("b");
    s2.add("c");
    Set<String> s3 = new HashSet<String>(s1);
    s1.removeAll(s2);
    s2.removeAll(s3);
    s1.addAll(s2);
    System.out.println(s1);

输出s1:[a,c]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM