0

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?

Community
  • 1
  • 1
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149

3 Answers3

1

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 called Iterators.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.

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
0

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!

paulsm4
  • 114,292
  • 17
  • 138
  • 190
0

Check out the Google Guava library, which includes a Iterators class containing many useful static methods. In this case, you can use concat to combine the iterators over each small collection into a single iterator that will traverse all collections.

// First collection.
List<String> l = new LinkedList<String>();
l.add("Hello");
l.add("Hi");

// Second collection.
Set<String> s = new HashSet<String>();
s.add("Goodbye");

// Combine iterators over both collections.
Iterator<String> it = Iterators.concat(l.iterator, s.iterator());
Adamski
  • 54,009
  • 15
  • 113
  • 152