java 将多个集合合并为一个集合并删除重复的集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6301510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
combining multiple sets into a single one and remove duplicate ones
提问by user785099
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.
我有 m 个集合,可以使用数组或数组列表存储。这些集合之间存在重叠。我想把这 m 个集合组合成一个集合,那些重复的元素只会在组合集合中占据一个位置。我应该使用哪种数据结构和操作来构造组合集。
采纳答案by Bohemian
This code will do it for you:
此代码将为您完成:
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
now contains all unique values once each
set
现在每个都包含所有唯一值
回答by u290629
See: javadoc of java.util.Set.addAll(Collection):
请参阅: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.
回答by Ondra ?i?ka
/**
* 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;
}
回答by Josh Lee
You should store them in a java.util.Set
in the first place.
您应该首先将它们存储在 ajava.util.Set
中。
回答by Urs Reupke
Apache Commonshas a ListOrderedSet. It combines the advantages of the Set (namely, each element occuring only once), with those of a list (iteration in the order of addition).
Apache Commons有一个 ListOrderedSet。它结合了 Set(即每个元素只出现一次)和列表(按添加顺序迭代)的优点。
With it, do what the others suggested:
有了它,按照其他人的建议去做:
- Construct a new ListOrderedSet lOS.
- Add all your elements into it using lOS.addAll(yourElements).
- 构造一个新的 ListOrderedSet lOS。
- 使用 lOS.addAll(yourElements) 将所有元素添加到其中。