是否有一个类表示一个集合与另一个集合的串联?此类本身应该是一个集合,并且应该将所有方法委托(delegate)给底层(内部)集合——不应分配额外的内存,也不应修改任何原始集合。
示例用法:
Collection<String> foo = ...
Collection<String> bar = ...
// this should be O(1) memory and time
Collection<String> combined = concat(foo, bar);
if (combined.contains("Zee"))
...
for (String str : combined)
System.out.println(str);
最佳答案
与往常一样,对于任何 Collection 品,请查看 google-collections .如果您有 Set
,特别是(不仅仅是一般集合),您需要:
Set<String> combined = Sets.union(foo, bar);
创建两个集合的不可修改的 View 。也就是说,foo
或 bar
中的更改将反射(reflect)在 combined
中(但 combined.add()
等是不支持)。
对于更通用的情况,您有 Iterables.concat()
但这仅允许您迭代连接的项目,Iterable
接口(interface)显然不包括 contains
所以你有点迷茫了。
google-collections 中的其他集合实用程序类(com.google.common.collect.Lists
和 com.google.common.collect.Collections2
)不包含任何连接方法。不明白他们为什么不能,但目前他们没有。
关于java - 表示 Java 中两个集合串联的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1738068/