2011-06-10 105 views
3

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

+0

A [设定](http://download.oracle.com/javase/1.5.0/docs/api/java/util/Set.html)? – jiggy 2011-06-10 02:58:17

回答

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现在包含各一次

1

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

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. 
0

Apache Commons有ListOrderedSet。它将Set的优点(即每个元素只出现一次)与列表(迭代顺序迭代)的优点结合起来。

有了它,做什么其他建议:

  • 构造一个新的ListOrderedSet洛杉矶。
  • 使用lOS.addAll(yourElements)将所有元素添加到它中。
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; 
}