Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 689
Simeon Avatar asked Nov 09 '11 11:11

Simeon


People also ask

How do you find the symmetric difference between two sets?

The symmetric difference of two sets A and B is the set (A – B) ∪ (B – A) and is denoted by A △ B. The shaded part of the given Venn diagram represents A △ B. A △ B is the set of all those elements which belongs either to A or to B but not to both. A △ B is also expressed by (A ∪ B) - (B ∩ A).

Which function will return the symmetric difference between two sets?

Explanation: The function x ^ y returns the symmetric difference between the two sets x and y.

What is symmetric difference between two sets with example?

In mathematics, we want to eliminate ambiguity. So the word 'or' in mathematics has an inclusive sense. For an example of the symmetric difference, we will consider the sets A = {1,2,3,4,5} and B = {2,4,6}. The symmetric difference between these sets is {1,3,5,6}.

Which operator is used for symmetric difference in set operation?

There is also another method to get the symmetric difference between two sets, by the use of an operator “^“. # using ^ operator.


1 Answers

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.

like image 124
Philipp Wendler Avatar answered Sep 19 '22 11:09

Philipp Wendler