Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding elements from two Sets

Tags:

java

int

set

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?

like image 831
Macosx Iam Avatar asked Nov 07 '11 03:11

Macosx Iam


People also ask

Can we add two sets?

Addition of sets A and B, referred to as Minkowski addition, is the set in whose elements are the sum of each possible pair of elements from the 2 sets (that is one element is from set A and the other is from set B).


2 Answers

Use Set.addAll()

Set<Integer> one = new HashSet<Integer>();
Set<Integer> two = new HashSet<Integer>();
Set<Integer> newSet = new HashSet<Integer>(one);
newSet.addAll(two);

Also, you should type your constructors (as above).

To make this into a method, try this:

public static Set<Integer> addTwoSets(Set<Integer> one, Set<Integer> two) {
    Set<Integer> newSet = new HashSet<Integer>(one);
    newSet.addAll(two);
    return newSet;
}

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:

public static <T> Set<T> merge(Collection<? extends T>... collections) {
    Set<T> newSet = new HashSet<T>();
    for (Collection<? extends T> collection : collections)
        newSet.addAll(collection);
    return newSet;
}

Or Java 8+:

public static <T> Set<T> merge(Collection<? extends T>... collections) {
    return Arrays.stream(collections).flatMap(Collection::stream).collect(toSet());
}
like image 95
Bohemian Avatar answered Sep 20 '22 09:09

Bohemian


You don't want a Set. As you have discovered, they do not have duplicate elements, by definition. You are looking for a Multiset (in fact, a SortedMultiset by the looks of it), also known as a Bag. Java doesn't have one out of the box, but there are open source implementations available, for example, Google's.

EDIT: Also, you want to do setOne.addAll(setTwo), not one element at a time, as commented above, but that is the secondary problem.

like image 24
Andrew Lazarus Avatar answered Sep 20 '22 09:09

Andrew Lazarus