我有m套,可以使用数组或arraylist存储。这些集合之间存在重叠。我想将这些m组合成一组,这些重复元素只占据组合集中的一个点。我应该使用哪种数据结构和操作来构造组合集。
答案 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的优点(即每个元素只出现一次)和列表的优点(迭代按加法顺序)。
有了它,做其他人的建议:
答案 5 :(得分:0)
在 Java 8 中,您可以使用流将多个集合组合为一个
Set<Long> ALL_IN_ONE = Stream.of(SET1, SET2).flatMap(Set::stream).collect(Collectors.toSet());