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.
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.
/**
* 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With