How can I add elements from two sets?
If there's a set one (1, 3, 6, 8)
And a set two (2, 4, 6, 8)
How do I the elements from those two together?
Output should be (1, 2, 3, 4, 6, 8)
Here’s what I tried:
Set<Integer> one = new HashSet();
one.add(1);
one.add(3);
// and so on
Set<Integer> two = new HashSet();
two.add(2);
two.add(4);
// and so on
Set<Integer> newSet = new HashSet();
newSet.add(one);
newSet.add(two);
return newSet;
And this doesn’t work, as the add method works only for a single integer, not a collection of integer. Is there a method where I can add two sets together?
I also have to return the set. How do I do that?
Use
Set.addAll()Also, you should type your constructors (as above).
To make this into a method, try this:
Let’s go nuts… here’s a method that will take any number of collections of any type that extends the desired type, and merges them into one set:
Or Java 8+: