There are two TreeSet
s in my app:
set1 = {501,502,503,504}
set2 = {502,503,504,505}
I want to get the symmetric difference of thes
Those looking for set subtraction/complement (not symmetric difference/disjunction) can use CollectionUtils.subtract(a,b) or Sets.difference(a,b).
use retain all,remove all then addAll to do a union of existing set.
- intersectionSet.retainAll(set2) // intersectionSet is a copy of set1
- set1.addAll(set2); // do a union of set1 and set2
- then remove the duplicates set1.removeAll(intersectionSet);
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);
output of s1 : [a,c]
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
if we use package com.google.common.collect, we may ellegantly find symmetric difference like this :
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 ));
The output will be : [1, 5]
You could try Sets.symmetricDifference()
from Eclipse Collections.
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);
Note: I am a committer for Eclipse Collections.