将多个集合合并为一个集合并删除重复的集合

问题描述

| 我有m套,可以使用数组或arraylist进行存储。这些集合之间存在重叠。我想将这m个集合合并为一个集合,而那些重复的元素将仅在合并的集合中占据一个位置。我应该使用哪种数据结构和操作来构造组合集。     

解决方法

        此代码将为您完成:
    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
1ѭ现在包含所有唯一值     ,        请参阅:java.util.Set.addAll(Collection)的javadoc:
/**
 * 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;
}
    ,        首先应将它们存储在ѭ4中。     ,        Apache Commons有一个ListOrderedSet。它结合了Set的优点(即每个元素仅出现一次)和列表的优点(按添加顺序迭代)。 使用它,执行其他人建议的操作: 构造一个新的ListOrderedSet lOS。 使用lOS.addAll(yourElements)将所有元素添加到其中。