## What is the best way get the symmetric difference between two sets in java?

java get difference between two collections

java set difference

symmetric difference of three sets

ruby set symmetric difference

symmetric difference set theory proof

symmetric difference kotlin

symmetric difference javascript

I'm wondering if there is a quick/clean way to get the symmetric difference between two sets ?

I have:

Set<String> s1 = new HashSet<String>(); s1.add("a"); s1.add("b"); s1.add("c"); Set<String> s2 = new HashSet<String>(); s2.add("b");

I need something like:

Set<String> diff = Something.diff(s1, s2); // diff would contain ["a", "c"]

Just to clarify I need the **symmetric** difference.

You can use some functions from the Google Guava library (which is really great, I strongly recommend it!):

Sets.difference(s1, s2); Sets.symmetricDifference(s1, s2);

Javadocs for difference() and symmetricDifference()

`symmetricDifference()`

does exactly what you are asking for, but `difference()`

is also often helpful.

Both methods return a live view, but you can for example call `.immutableCopy()`

on the resulting set to get a non-changing set. If you don't want a view, but need a set instance you can modify, call `.copyInto(s3)`

. See SetView for these methods.

**Symmetric difference of two sets in Java,** Possible duplicate of What is the best way get the symmetric difference between two sets in java? addAll(set2); // symmetricDiff now contains the union Set<Type> tmp = new removeAll(tmp); // union minus intersection equals symmetric-difference we may ellegantly find symmetric difference like this : If an actual java.util.Set is required, instead of any collection that in this case behaves as a set, one may use a java.util.SortedSet implementation (e.g., java.util.TreeSet). The code above can be directly translated to iterators by using a PeekableIterator wrapper.

You want the symmetric difference.

public static <T> Set<T> diff(final Set<? extends T> s1, final Set<? extends T> s2) { Set<T> symmetricDiff = new HashSet<T>(s1); symmetricDiff.addAll(s2); Set<T> tmp = new HashSet<T>(s1); tmp.retainAll(s2); symmetricDiff.removeAll(tmp); return symmetricDiff; }

If you want a library, Apache Commons CollectionUtils has

CollectionUtils.disjunction(s1, s2)

which returns a non-generic `Collection`

.

and Guava Sets has

Sets.symmetricDifference(s1, s2)

which returns an unmodifiable `Set`

as a generic `Sets.SetView`

.

Guava is a bit more modern, supporting generics, but either of these will work.

**Symmetric difference of two sorted array,** We use cookies to ensure you have the best browsing experience on our website. Symmetric difference of two array is the all array elements of both array except the An Efficient solution for find the symmetric difference of two sorted arrays is similar to merge process of merge sort. Java program to find the symmetric. (The union of two sets is the set containing all of the elements contained in either set.) s1.retainAll(s2) — transforms s1 into the intersection of s1 and s2. (The intersection of two sets is the set containing only the elements common to both sets.) s1.removeAll(s2) — transforms s1 into the (asymmetric) set difference of s1 and s2.

If you can use Apache-Commons Collections, you are looking for `CollectionUtils.disjunction(Collection a, Collection b)`

. It returns the symmetric difference of both Collections.

If not, substract (`removeAll`

) the intersection (`retainAll`

) of both sets to the union of both (`addAll`

):

Set<String> intersection = new HashSet<String>(set1); intersection.retainAll(set2); Set<String> difference = new HashSet<String>(); difference.addAll(set1); difference.addAll(set2); difference.removeAll(intersection);

**Symmetric difference of two sets,** find difference in sets java sets difference set operations in java code. I'm wondering if there is a quick/clean way to get the symmetric difference between two The difference of two sets, written A - B is the set of all elements of A that are not elements of B. The difference operation, along with union and intersection, is an important and fundamental set theory operation.

**Loop through one set and compare.**

It's only `O(n)`

to loop through one of the sets. Consider this code:

for (String key: oldSet) { if (newSet.contains(key)) newSet.remove(key); else newSet.add(key); }

And the `newSet`

will now contain only the unique entries from both sets. It's fast, because you only need to loop through the elements in one of the sets and you don't have to create sets unless you explicitly need a copy.

**How to get symmetric difference of two sets – example,** This snippet will find the difference between two collections specifically two sets using core JDK. We will first combine or add Difference Between Symmetric and Asymmetric Encryption Symmetric encryption uses a single key that needs to be shared among the people who need to receive the message while asymmetrical encryption uses a pair of public key and a private key to encrypt and decrypt messages when communicating.

public class Practice { public static void main(String[] args) { Set<Integer> set1 = new HashSet<Integer>(); Set<Integer> set2 = new HashSet<Integer>(); set1.add(1); set1.add(4); set1.add(7); set1.add(9); set2.add(2); set2.add(4); set2.add(5); set2.add(6); set2.add(7); symmetricSetDifference(set1, set2); } public static void symmetricSetDifference(Set<Integer>set1, Set<Integer>set2){ //creating a new set Set<Integer> newSet = new HashSet<Integer>(set1); newSet.removeAll(set2); set2.removeAll(set1); newSet.addAll(set2); System.out.println(newSet); }

}

**Symmetric difference,** Set<Character> bc = new HashSet<Character>(Arrays.asList( 'b' , 'c' ));. // Symmetric difference of two sets. Set<Character> intersection = new Set is an interface which extends Collection. It is an unordered collection of objects in which duplicate values cannot be stored. Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation). Set has various methods to add, remove clear, size, etc to enhance the usage of this interface.

**Get the asymmetric difference of two sets in Java,** If your code uses lists of items to represent sets then ensure duplicate items in lists are correctly handled. For example two lists representing Symmetric Difference as a Metric. and identify the sets that agree up to a null set. After that, the first two axioms are clear, and only the triangle inequality

**Guava,** Use removeAll() method to get the asymmetric difference of two sets.First set −HashSet set1 = new HashSet (); set1.add(Mat); set1.add(Sat Difference between two sets in Python is equal to the difference between the number of elements in two sets. The function difference () returns a set that is is the difference between two sets. Let’s try to find out what will be the difference between two sets A and B.

**Sets (Guava: Google Core Libraries for Java 22.0 API),** Next – let's see how to get the intersection between two sets – using difference of two sets – all elements that are contained in either set 1 or set 2 but not in both: ? This type of data structure is of course something you can do in plain Java First – it's because I believe they're done better on Baeldung. The difference() method returns the set difference of two sets. If A and B are two sets. The set difference of A and B is a set of elements that exists only in set A but not in B .

##### Comments

- Quick&easy: You could write Set<String> diff = new HashSet<String>(s1); diff.removeAll(s2);
- @polkageist: it will fail for S1={"a","b","c"},S2={"b","d"}. result should be {"a","c","d"}
- If by "difference" (cf. secure.wikimedia.org/wikipedia/en/wiki/…) the OP meant symmetric difference, then you're right. However, you can get this as either (A - B) + (B - A), or (A + B) - (A cap B). I don't know any quicker way in java to implement that.
- Java 8 and Java 11 : stackoverflow.com/a/52268640/1216775
- Having just read the javadoc for symetricDifference(), I'm a bit concerned about this statement "Results are undefined if set1 and set2 are sets based on different equivalence relations (as
**HashSet**, TreeSet, and the keySet of an IdentityHashMap all are)." That makes it sound like the results are undefined for the OP's case (and the Sets.symmetricDifference() method seems not so useful. - @Gus The JavaDoc wants to say that the results are undefined, if you use the method with two different sets that use different equivalence relations, for example, computing the difference between a
`HashSet`

and a`TreeSet`

may be problematic. Using the method with two`HashSet`

s, or two`TreeSets`

, etc. is fine. - @Gus Furthermore it is also fine if you use the method with a
`HashSet`

and a`TreeSet`

, if the`compareTo()`

method and the`equals()`

method of the elements agree with each other (which is strongly recommended by their documentation). So only in special cases the method cannot guarantee that the difference is computed correctly, in most practical cases it will work fine. - I had the same concern about that "results are undefined" statement. Thank you @PhilippWendler for clarifying this!
- thanks, I was actually looking for a lib that does it for me, as this is what I've currently done
- CollectionUtils from Apache Commons Collections v4+ support generics
- Note that this is
`O(n)`

for`HashSet`

with no collision only. For TreeSets, all three operations`add(key)`

,`contains(key)`

and`remove(key)`

would require searching the tree once, i.e. an additional`O(n log n)`

. - Although this code may answer the question, providing additional context regarding
*why*and/or*how*it answers the question would significantly improve its long-term value. Please edit your answer to add some explanation. - This will fail for S1={"a","b","c"},S2={"b","d"}. Result should be {"a","c","d"}.
- This is an asymmetric difference. He wants the symmetric difference.