Write a method called symmetricSetDifference that accepts two Sets as parameters and returns a new Set containing their symmetric set difference (that is, the set of elements contained in either of the two sets but not in both). For example, the symmetric difference between the sets {1, 4, 7, 9} and {2, 4, 5, 6, 7} is {1, 2,5, 6, 9}.
// package collections;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class SetDiffrence {
public static Set<String> symmetricSetDiffrence(Set<String> set1, Set<String> set2) {
// Set doesn't allow duplicates thus adding both gives us the symmetric set diffrence.
set1.addAll(set2);
set1 = (HashSet<String>) set1;
return set1;
}
public static void main(String args[]) {
Set<String> set1 = new HashSet<String>();
Set<String> set2 = new HashSet<String>();
Collections.addAll(set1, "a", "b", "c", "d");
Collections.addAll(set2, "b", "k", "d", "a");
System.out.print("the symmetric set diffrence is: [ ");
Set<String> unique = SetDiffrence.symmetricSetDiffrence(set1, set2);
for (String s : unique)
System.out.print(s+" ");
System.out.print("]");
}
}
Output:
the symmetric set diffrence is: [ a b c d k ]