Igor Kromin |   Consultant. Coder. Blogger. Tinkerer. Gamer.

Java Iterators are great. They provide an easy way of traversing a data structure without having to use a counter loop and without having to worry about how the data structure itself is implemented, you simply check if the Iterator has a next value and then get that value. Easy!

Now what if you had multiple Iterators and you wanted to process data from all of them? An example of this is if you have a number of Threads (or FutureTasks) that retrieve data from the database and then return an Iterator to the processed data. That becomes a little bit more challenging.

You'd have to have a way of combining these Iterators somehow...or chaining them to look like one single Iterator.

The IteratorChain class from Apache Commons does exactly this!

Since IteratorChain implements the Iterator interface, you can use it in place of any other standard Iterator. To use IteratorChain, either initialise it with a Collection of Iterator objects or call the addIterator() method to add all your Iterators to the chain.

The caveat is all your Iterators have to return the same data type. However if that is already the case, IteratorChain saves a good amount of work.



-i

Hope you found this post useful...

...so please read on! I love writing articles that provide beneficial information, tips and examples to my readers. All information on my blog is provided free of charge and I encourage you to share it as you wish. There is a small favour I ask in return however - engage in comments below, provide feedback, and if you see mistakes let me know.

If you want to show additional support and help me pay for web hosting and domain name registration, donations, no matter how small, are always welcome!

Use of any information contained in this blog post/article is subject to this disclaimer.
comments powered by Disqus
Other posts you may like...