I am trying to find the uncommon elements from two sets in Java. Here is my way:
private void findUnCommon{
Set<Integer> a = new HashSet<>(Arrays.asList(1, 2, 3, 4));
Set<Integer> b = new HashSet<>(Arrays.asList(3, 4, 5, 6));
// get all elements from set a and set b
System.out.println("Before..");
System.out.println("a is : " + a);
System.out.println("b is : " + b);
Set<Integer> result = new HashSet<>(a);
result.removeAll(b);
System.out.println("result is : " + result);
Set<Integer> temp = new HashSet<>(b);
temp.removeAll(a);
System.out.println("temp is : " + temp);
result.addAll(temp);
System.out.println("Uncommon elements of set a and set b is : "
+ result);
System.out.println("After..");
System.out.println("a is : " + a);
System.out.println("b is : " + b);
}
I have declared two extra sets. Can this be improved?