Java中两组的对称差异

我的应用程序中有两个TreeSet

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

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

 set = {501,505} 

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

 Set symmetricDiff = new HashSet(set1); symmetricDiff.addAll(set2); // symmetricDiff now contains the union Set tmp = new HashSet(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

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

使用retain all,删除all然后addAll来执行现有set的联合。

  1. intersectionSet.retainAll(set2)// intersectionSet是set1的副本
  2. set1.addAll(SET2); //做一个set1和set2的联合
  3. 然后删除重复项set1.removeAll(intersectionSet);
 Set s1 = new HashSet(); Set s2 = new HashSet(); s1.add("a"); s1.add("b"); s2.add("b"); s2.add("c"); Set s3 = new HashSet(s1); s1.removeAll(s2); s2.removeAll(s3); s1.addAll(s2); System.out.println(s1); 

输出s1:[a,c]

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

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

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