So if I have two sets:
Set<Integer> test1 = new HashSet<Integer>();
test1.add(1);
test1.add(2);
test1.add(3);
Set<Integer> 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?
You can use
CollectionUtils.disjunction
to get all differences orCollectionUtils.subtract
to get the difference in the first collection.Here is an example of how to do that:
Yes:
Although this will mutate
test2
, so create a copy if you need to preserve it.Also, you probably meant
<Integer>
instead of<int>
.Try this
Set#removeAll
Just to put one example here (system is in
existingState
, and we want to find elements to remove (elements that are not innewState
but are present inexistingState
) and elements to add (elements that are innewState
but are not present inexistingState
) :would output this as a result:
Java 8
We can make use of removeIf which takes a predicate to write a utility method as:
And in case we are still at some prior version then we can use removeAll as:
If you use Guava (former Google Collections) library there is a solution:
The returned
SetView
is aSet
, it is a live representation you can either make immutable or copy to another set.test1
andtest2
are left intact.