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(); ..... }
If you are given two Iterators in Java, how are you supposed to merge them into one list if both iterators are sorted? The Java's iterator has two important methods you can use: hasNext() and next(). The hasNext() returns a boolean telling if this iterator reaches the end.
iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.
Realize that elements could be mutable (or reference dynamic values) and they may reference other structures and semantics which require a customized copy function. Thus copyable iterators is not orthogonal to copyable stream elements, so this is why copyable iterators are not possible in general.
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
Guava (formerly Google Collections) has Iterators.concat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With