Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symmetric difference of two sets in Java

There are two TreeSets in my app:

set1 = {501,502,503,504} set2 = {502,503,504,505} 

I want to get the symmetric difference of these sets so that my output would be the set:

set = {501,505} 
like image 597
Abhij Avatar asked Mar 14 '12 09:03

Abhij


People also ask

What is the symmetric difference of two sets?

The symmetric difference of set A with respect to set B is the set of elements which are in either of the sets A and B, but not in their intersection. This is denoted as A△B or A⊖B or.

What is symmetric difference in Java?

Symmetric Difference basically contains all elements of two arrays except common elements. Symmetric difference of two array is the all array elements of both array except the elements that are presents in both array. SymmDiff = (arr1 - arr2) UNION (arr2 - arr1).

What is the difference between difference and symmetric difference?

The symmetric difference of two sets A and B is the set of elements which are in either of the sets A or B but not in both. However the difference of course, is self explanatory. I hadn't pay attention to "either" key word in definition. thanks.


1 Answers

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 
like image 160
Donal Fellows Avatar answered Oct 04 '22 06:10

Donal Fellows