Java 方法将多个集合作为一个整体进行访问,无需连接
可能的重复:
将多个集合合并为一个逻辑集合?
我有一个我想作为一个整体访问很多小收藏。
例如,我可以创建一个新的 LinkedList 并向其中添加所有元素。但我在想,可能有一些工具可以添加完整的集合
,而无需重新链接每个项目。我不是在谈论 addAll
。 Collections
应保持独立,但仅从外部看来是一个整体。
有什么想法吗?
Possible Duplicate:
Combine multiple Collections into a single logical Collection?
I have a lot of small collections that I would like to access as a whole.
I could e.g. create a new LinkedList
and add all elements to it. But I was thinking, there might be some tool to add complete Collections
without having to re-link every item. I am not speaking about addAll
. The Collections
shall stay seperate, but only from the outside seem to be one.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Google Guava 项目有一个名为
Iterators
的类,它提供了用于获取迭代器并向其应用转换的实用程序。他们提供的函数之一称为Iterators.concat
,它接受多个迭代器并生成一个对串联进行迭代的新迭代器这些单独的迭代器。这可能不完全是您正在寻找的,但它将为您提供跨多个元素进行迭代的功能,而无需复制所有元素。在按照您的建议使用集合时,您可能需要考虑的一个问题是,如果您尝试改变集合会发生什么。例如,如果添加一个元素,它会去哪里?如果您需要的只是迭代并且不需要考虑这一点,那么
Iterators.concat
方法可能就是您正在寻找的。The Google Guava project has a class called
Iterators
that provides utilities for taking iterators and applying transforms to them. One of the functions they provide is calledIterators.concat
, which takes in multiple iterators and produces a new iterator that iterates over the concatenation of those individual iterators. This may not be exactly what you're looking for, but it would provide you the functionality of iterating across multiple elements without having to duplicate all of them.One question you may need to think about when using a collection as you've proposed is what happens if you try to mutate the collection. For example, if you add an element, where would it go? If all you need is iteration and you don't need to think about this, the
Iterators.concat
method may be what you're looking for.在标准 Java 中,您能做的最好的事情就是创建集合的集合。
如果您要采用“guava”,则可以使用“Iterable”来创建这样一个野兽:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#concat%28java.lang.Iterable,java.lang.Iterable, java.lang.Iterable%29
PS:
说“嗨!”替我向格雷戈尔·萨姆萨致敬!
In standard Java, the best you can do is to create a collection of collections.
If you were to adopt "guava", you could use "Iterable" to create such a beast:
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Iterables.html#concat%28java.lang.Iterable,java.lang.Iterable,java.lang.Iterable%29
PS:
Say "Hi!" to Gregor Samsa for me!
查看 Google Guava 库,其中包含一个
Iterators
类,其中包含许多有用的静态方法。在这种情况下,您可以使用concat
将每个小集合上的迭代器组合成一个将遍历所有集合的迭代器。Check out the Google Guava library, which includes a
Iterators
class containing many useful static methods. In this case, you can useconcat
to combine the iterators over each small collection into a single iterator that will traverse all collections.