Find the uncommon elements from two sets I am trying to find the uncommon elements from two sets in Java. Here is my way:

private void findUnCommon{

    Set&lt;Integer&gt; a = new HashSet&lt;&gt;(Arrays.asList(1, 2, 3, 4));
    Set&lt;Integer&gt; b = new HashSet&lt;&gt;(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&lt;Integer&gt; result = new HashSet&lt;&gt;(a);
    result.removeAll(b);
    System.out.println("result is : " + result);

    Set&lt;Integer&gt; temp = new HashSet&lt;&gt;(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?
Is this a method?  You can't just plop code anywhere in Java.

The name of the operation is symmetric difference, so you should probably call it that.

Here's a more compact implementation.

private Set&lt;T&gt; symmetricDifference(Set&lt;T&gt; a, Set&lt;T&gt; b) {
    Set&lt;T&gt; result = new HashSet&lt;T&gt;(a);
    for (T element : b) {
        // .add() returns false if element already exists
        if (!result.add(element)) {
            result.remove(element);
        }
    }
    return result;
}