package org.metaborg.util.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Queue;

import com.google.common.collect.Queues;

public class CompoundIterator<T> implements Iterator<T> {
    private final Queue<? extends Iterator<T>> iterators;


    public CompoundIterator(Iterable<? extends Iterator<T>> iterators) {
        this.iterators = Queues.newArrayDeque(iterators);
    }


    @Override public boolean hasNext() {
        final Iterator<T> iterator = iterators.peek();
        if(iterator == null) {
            return false;
        }
        return iterator.hasNext();
    }

    @Override public T next() {
        final Iterator<T> iterator = iterators.peek();
        if(iterator == null) {
            throw new NoSuchElementException();
        }

        if(iterator.hasNext()) {
            return iterator.next();
        } else {
            iterators.poll();
            return next();
        }
    }

    @Override public void remove() {
        throw new UnsupportedOperationException();
    }
}

@@ -102,32 +102,8 @@
 ion;
-%0Aimport java.util.Queue;
 %0A%0Aim
@@ -133,21 +133,24 @@
 collect.
-Queue
+Iterator
 s;%0A%0Apubl
@@ -221,21 +221,24 @@
 e final 
-Queue
+Iterator
 %3C? exten
@@ -264,16 +264,78 @@
 rators;%0A
+    private Iterator%3CT%3E iterator = Iterators.emptyIterator();%0A
 %0A%0A    pu
@@ -430,37 +430,26 @@
 s = 
-Queues.newArrayDeque(
+iterators.
 iterator
 s);%0A
@@ -444,17 +444,17 @@
 iterator
-s
+(
 );%0A    %7D
@@ -505,33 +505,101 @@
         
-final Iterator%3CT%3E
+if(iterator.hasNext()) %7B%0A            return true;%0A        %7D%0A        try %7B%0A           
  iterato
@@ -604,36 +604,36 @@
 tor = iterators.
-peek
+next
 ();%0A        if(i
@@ -628,35 +628,49 @@
         
-if(iterator == null
+%7D catch(NoSuchElementException ex
 ) %7B%0A    
@@ -716,25 +716,16 @@
  return 
-iterator.
 hasNext(
@@ -778,63 +778,26 @@
     
-final Iterator%3CT%3E iterator = iterators.peek();%0A
+try %7B%0A    
         
 if(i
@@ -792,27 +792,31 @@
         
-if(
+return 
 iterator
  == null
@@ -811,42 +811,33 @@
 ator
- == null) %7B%0A            throw new 
+.next();%0A        %7D catch(
 NoSu
@@ -850,27 +850,30 @@
 entException
-();
+ ex) %7B
 %0A        %7D%0A%0A
@@ -873,62 +873,22 @@
     
-%7D%0A%0A        if(iterator.hasNext()) %7B%0A            return
+    iterator =
  ite
@@ -884,32 +884,33 @@
 rator = iterator
+s
 .next();%0A       
@@ -915,50 +915,9 @@
    %7D
- else %7B%0A            iterators.poll();%0A    
+%0A
     
@@ -931,34 +931,24 @@
 urn next();%0A
-        %7D%0A
     %7D%0A%0A    @

Fix compound iterator for case where empty iterators appear in the list.