Skip to content

Instantly share code, notes, and snippets.

@hussachai
Last active November 18, 2015 17:34
Show Gist options
  • Save hussachai/4795152d89ad7d4ef833 to your computer and use it in GitHub Desktop.
Save hussachai/4795152d89ad7d4ef833 to your computer and use it in GitHub Desktop.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.NoSuchElementException;
/**
*
* @author Hussachai
*
* @param <T>
*/
public class MultiIterator<T> implements Iterator<T>{
private List<Iterator<T>> iterators = new ArrayList<Iterator<T>>();
private int current = 0; /* iterator idx 0 - iterators.size() - 1 */
public MultiIterator(Iterator<Iterator<T>> iterators){
iterators.forEachRemaining(elem -> this.iterators.add(elem));
}
@Override
public boolean hasNext() {
for(Iterator<T> iterator: iterators) if(iterator.hasNext()) return true;
return false;
}
@Override
public T next() {
for(int i = 0; i < iterators.size(); i++){
Iterator<T> iterator = iterators.get(current);
if(++current >= iterators.size()) current = 0;
if(iterator.hasNext()) return iterator.next();
}
throw new NoSuchElementException();
}
public static void main(String[] args) {
List<Integer> a = new LinkedList<>();
a.add(1);
a.add(7);
a.add(13);
a.add(17);
List<Integer> b = new LinkedList<>();
b.add(2);
b.add(8);
b.add(14);
b.add(18);
List<Integer> c = new LinkedList<>();
c.add(3);
c.add(9);
List<Integer> d = new LinkedList<>();
d.add(4);
d.add(10);
d.add(15);
List<Integer> e = new LinkedList<>();
e.add(5);
e.add(11);
List<Integer> f = new LinkedList<>();
f.add(6);
f.add(12);
f.add(16);
f.add(19);
List<Iterator<Integer>> iterators = new LinkedList<>();
iterators.add(a.iterator());
iterators.add(b.iterator());
iterators.add(c.iterator());
iterators.add(d.iterator());
iterators.add(e.iterator());
iterators.add(f.iterator());
MultiIterator<Integer> it = new MultiIterator<>(iterators.iterator());
while (it.hasNext()) {
System.out.print(it.next() + ","); // prints: 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment