import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
public class IteratorExample {
static List<String> l1 = Arrays.asList("l1", "l1b");
static List<String> l2 = Arrays.asList("l2", "l2b");
static List<String> l3 = Arrays.asList("l3", "l3b");
static List<String> l4 = Arrays.asList("l4", "l4b");
// Exercise: create a method that takes an number of iterables and returns a single unified iterator.
static Iterator<String> getIterator(Iterable<String> ... iterables){
return new MyIterator(iterables);
}
public static void main (String [] args) {
Iterator<String> custIterator = getIterator(l1, l2, l3, l4);
while (custIterator.hasNext()){
System.out.println(custIterator.next());
}
}
}
class MyIterator implements Iterator<String>{
private int curItIndex = -1;
private Iterator<String> curIt;
private Iterable<String>[] iterables;
MyIterator(Iterable<String>[] iterables){
this.iterables = iterables;
if (this.iterables != null && this.iterables.length > 0) {
this.curItIndex = 0;
this.curIt = this.iterables[curItIndex].iterator();
}
}
@Override
public boolean hasNext() {
// no iterables provided
if (curItIndex == -1) return false;
if (curIt.hasNext()) {
return true;
} else {
curItIndex++;
}
// basically, if the current iterator has run dry try the next one
while (curItIndex < iterables.length) {
curIt = iterables[curItIndex].iterator();
if(curIt.hasNext())
return true;
else
curItIndex++;
}
return false;
}
@Override
public String next() {
if (hasNext()) {
return curIt.next();
} else {
throw new NoSuchElementException();
}
}
}