Merge multiple sets into one and remove duplicates

I have m sets that can be saved using an array or arraylist. There are overlaps between these sets. I would like to combine these m-sets into one set, and these repeating elements will occupy only one place in the combined set. What data structure and operation should be used to build a combined set.

+3
source share
5 answers

This code will do it for you:

    Set set = new HashSet();
    ArrayList list = new ArrayList();
    ArrayList list2 = new ArrayList(); //etc
    Object[] array = new Object[]{};
    Object[] array2 = new Object[]{}; // etc
    set.addAll(list);
    set.addAll(list2);
    set.addAll(Arrays.asList(array));
    set.addAll(Arrays.asList(array2));
    // Call addAll as many times as you like

set now contains all unique values ​​after each

+2
source

See: javadoc from java.util.Set. addAll (collection):

/**
 * Adds all of the elements in the specified collection to this set if
 * they're not already present (optional operation).  If the specified
 * collection is also a set, the <tt>addAll</tt> operation effectively
 * modifies this set so that its value is the <i>union</i> of the two
 * sets.  The behavior of this operation is undefined if the specified
 * collection is modified while the operation is in progress.
+4
source
/**
 * Join multiple sets into one.
 */
@SafeVarargs
private final <T> Set<T> join(Set<T>... sets)
{
    Set<T> result = new HashSet<>();
    if (sets == null)
        return result;

    for (Set<T> set : sets)
    {
        if (set != null)
            result.addAll(set);
    }
    return result;
}
+2

java.util.Set.

+1

Apache Commons has a ListOrderedSet. It combines the advantages of Set (namely, each element takes place only once), as well as the list of the list (iteration in the order of adding).

With this, do what others have suggested:

  • Create a new ListOrderedSet lOS object.
  • Add all your elements to it using lOS.addAll (yourElements).
0
source

All Articles