Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining multiple sets into a single one and remove duplicate ones

Tags:

java

I have m sets, which can be stored using array, or arraylist. There are overlaps among these sets. I would like to combine these m sets into a single set, and those duplicate elements will only occupy one spot in the combined set. Which kind of data structure and operation should I use to construct the combined set.

like image 414
user785099 Avatar asked Dec 29 '25 02:12

user785099


2 Answers

See: javadoc of 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.
like image 121
卢声远 Shengyuan Lu Avatar answered Dec 31 '25 15:12

卢声远 Shengyuan Lu


/**
 * 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;
}
like image 22
Ondra Žižka Avatar answered Dec 31 '25 16:12

Ondra Žižka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!