Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to merge iterators in Java?

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();   ..... } 
like image 579
Jahanzeb Farooq Avatar asked Aug 31 '10 14:08

Jahanzeb Farooq


People also ask

How do I combine two iterators in Java?

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.

Can iterators be reused?

iterators are not reusable; you need to get a fresh Iterator from the Iterable collection each time you want to iterate over the elements.

Why are iterators not copyable?

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.

Are iterators better than for loops?

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.


1 Answers

Guava (formerly Google Collections) has Iterators.concat.

like image 84
Andrew Duffy Avatar answered Sep 16 '22 16:09

Andrew Duffy