David Tunnell David Tunnell - 6 months ago 21
Java Question

Getting the difference between two sets

So if I have two sets:

Set<int> test1 = new HashSet<Integer>();
test1.add(1);
test1.add(2);
test1.add(3);

Set<int> test2 = new HashSet<Integer>();
test2.add(1);
test2.add(2);
test2.add(3);
test2.add(4);
test2.add(5);


Is there a way to compare them and only have a set of 4 and 5 returned?

Answer

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.

Comments