Is it possible to merge iterators in Java? I have two iterators and I want to combine/merge them so that I could iterate though their elements in one go (in same loop) rather than two steps. Is that possible?
Note that the number of elements in the two lists can be different therefore one loop over both lists is not the solution.
Iterator<User> pUsers = userService.getPrimaryUsersInGroup(group.getId());
Iterator<User> sUsers = userService.getSecondaryUsersInGroup(group.getId());
while(pUsers.hasNext()) {
User user = pUsers.next();
.....
}
while(sUsers.hasNext()) {
User user = sUsers.next();
.....
}
You could create your own implementation of the
Iterator
interface which iterates over the iterators:(I've not added generics to the Iterator for brevity.) The implementation is not too hard, but isn't the most trivial, you need to keep track of which
Iterator
you are currently iterating over, and callingnext()
you'll need to iterate as far as you can through the iterators until you find ahasNext()
that returnstrue
, or you may hit the end of the last iterator.I'm not aware of any implementation that already exists for this.Update:
I've up-voted Andrew Duffy's answer - no need to re-invent the wheel. I really need to look into Guava in more depth.
I've added another constructor for a variable number of arguments - almost getting off topic, as how the class is constructed here isn't really of interest, just the concept of how it works.
move your loop to a method and pass the iterator to method.
every
Iterator
object holds own memory location (adress), so you can't simply "merge" them. except if you extenditerator
class and write your own implementation there.If you are dealing with the same number of objects in both iterators an alternative solution would be to process two iterators in one loop like this :
Also the Apache Commons Collection have several classes for manipulating Iterators, like the IteratorChain, that wraps a number of Iterators.
I would refactor the original design from:
To something like: