Getting the difference between two sets Getting the difference between two sets java java

Getting the difference between two sets


Try this

test2.removeAll(test1);

Set#removeAll

Removes from this set all of its elements that are contained in the specified collection (optional operation). If the specified collection is also a set, this operation effectively modifies this set so that its value is the asymmetric set difference of the two sets.


If you use Guava (former Google Collections) library there is a solution:

SetView<Number> difference = com.google.common.collect.Sets.difference(test2, test1);

The returned SetView is a Set, it is a live representation you can either make immutable or copy to another set. test1 and test2 are left intact.


Yes:

test2.removeAll(test1)

Although this will mutate test2, so create a copy if you need to preserve it.

Also, you probably meant <Integer> instead of <int>.