将多个集合组合成一个集合并删除重复集合

时间:2011-06-10 02:55:59

标签: java

我有m套,可以使用数组或arraylist存储。这些集合之间存在重叠。我想将这些m组合成一组,这些重复元素只占据组合集中的一个点。我应该使用哪种数据结构和操作来构造组合集。

6 个答案:

答案 0 :(得分:4)

请参阅:java.util.Set的javadoc。 addAll (集合):

/**
 * 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.

答案 1 :(得分:2)

此代码将为您完成:

    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现在包含所有唯一值

答案 2 :(得分:2)

/**
 * 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;
}

答案 3 :(得分:1)

您应该首先将它们存储在java.util.Set中。

答案 4 :(得分:0)

Apache Commons有一个ListOrderedSet。它结合了Set的优点(即每个元素只出现一次)和列表的优点(迭代按加法顺序)。

有了它,做其他人的建议:

  • 构造一个新的ListOrderedSet lOS。
  • 使用lOS.addAll(yourElements)将所有元素添加到其中。

答案 5 :(得分:0)

Java 8 中,您可以使用将多个集合组合为一个

Set<Long> ALL_IN_ONE = Stream.of(SET1, SET2).flatMap(Set::stream).collect(Collectors.toSet());
相关问题