Java中两个集合的对称差[重复]

2024-02-16

那里有两个TreeSet在我的应用程序中:

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

我想要得到对称差异 https://en.wikipedia.org/wiki/Symmetric_difference这些集合,以便我的输出将是集合:

set = {501,505}

你在追寻对称差异 http://mathworld.wolfram.com/SymmetricDifference.html。这在Java教程 http://docs.oracle.com/javase/tutorial/collections/interfaces/set.html.

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java中两个集合的对称差[重复] 的相关文章

随机推荐