There are two TreeSet
s 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}
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With