tags:

views:

210

answers:

4

Is there an Iterator implementation that merges multiple iterators?

class MergedIterator<T> implements Iterator<T>
{
     MergedIterator(Iterator<T>... iters)
     ....
}

And the next method should move on to iters[1] when !iters[0].hasNext() etc

+11  A: 

I'd call that a ConcatenatedIterator myself - a MergedIterator should merge the results of several iterators e.g. based on sorting

Naming aside, I'm sure there'll be an implementation in a 3rd party library somewhere. Just off to check Google collections...

EDIT: Bingo - Iterators.concat

Jon Skeet
Or SequenceIterator, like SequenceInputStream.
Tom Hawtin - tackline
+3  A: 

Commons Collections IteratorChain

JodaStephen
+1  A: 

there's one in groovy: http://groovy.codehaus.org/Iterator+Tricks - you can probably roll one up like this with a few more lines of code.

Ray Tayek
A: 

@Jon Thanks a ton. Exactly what I need

@JodaStephen Almost works, but its not generic so I would go for Google collections

Hemal Pandya
Try using the "add comment" to respond instead of typing a new answer. And if you think he answered it, check it as the answer.
Josh