Wednesday, March 16, 2011

is there a merged iterator implementation?

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

From stackoverflow
  • 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

    Tom Hawtin - tackline : Or SequenceIterator, like SequenceInputStream.
  • Commons Collections IteratorChain

  • 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.

  • @Jon Thanks a ton. Exactly what I need

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

    Josh : 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.

0 comments:

Post a Comment