Symmetric Different two set in Java
Description
The following code shows how to symmetric Different two set.
Example
import java.util.Set;
import java.util.TreeSet;
/*from w w w . j av a2s . co m*/
public class Main {
public static <T> Set<T> symDifference(Set<T> setA, Set<T> setB) {
Set<T> tmpA;
Set<T> tmpB;
tmpA = union(setA, setB);
tmpB = intersection(setA, setB);
return difference(tmpA, tmpB);
}
public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>();
for (T x : setA)
if (setB.contains(x))
tmp.add(x);
return tmp;
}
public static <T> Set<T> difference(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>(setA);
tmp.removeAll(setB);
return tmp;
}
public static <T> Set<T> union(Set<T> setA, Set<T> setB) {
Set<T> tmp = new TreeSet<T>(setA);
tmp.addAll(setB);
return tmp;
}
public static void main(String args[]) {
Set<Character> set1 = new TreeSet<Character>();
Set<Character> set2 = new TreeSet<Character>();
set1.add('A');
set1.add('B');
set1.add('C');
set1.add('D');
set2.add('C');
set2.add('D');
set2.add('E');
set2.add('F');
System.out.println("set1: " + set1);
System.out.println("set2: " + set2);
System.out.println("Symmetric Difference: " + symDifference(set1, set2));
}
}
The code above generates the following result.