Java中两个集合的对称差分
2022-09-01 09:46:23
我的应用中有两个:TreeSet
set1 = {501,502,503,504}
set2 = {502,503,504,505}
我想得到这些集合的对称差,以便我的输出将是集合:
set = {501,505}
我的应用中有两个:TreeSet
set1 = {501,502,503,504}
set2 = {502,503,504,505}
我想得到这些集合的对称差,以便我的输出将是集合:
set = {501,505}
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