Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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?

1 Answer

0 votes
by (46k points)

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.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...