Java中两组的对称差异 [英] Symmetric difference of two sets in Java

查看:103
本文介绍了Java中两组的对称差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用中有两个 TreeSet

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

我想得到对称差异,以便我的输出为集合:

I want to get the symmetric difference of these sets so that my output would be the set:

set = {501,505}


推荐答案

您正在追踪对称差异。这在 Java教程中讨论。

You're after the symmetric difference. This is discussed in the Java tutorial.

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

这篇关于Java中两组的对称差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆