我有m个集合,可以使用array或arraylist来存储。这些集合之间存在重叠。我想把这m个集合合并成一个集合,而那些重复的元素只会占据组合集合中的一个位置。我应该使用哪种数据结构和操作来构造组合集。
发布于 2011-06-10 11:02:47
下面的代码将为您完成此操作:
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 likeset现在包含所有唯一值,每个值一次
发布于 2011-06-10 11:23:57
请参阅: 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.发布于 2016-05-05 22:58:00
/**
* 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;
}https://stackoverflow.com/questions/6301510
复制相似问题