Skip to content

Instantly share code, notes, and snippets.

@pravsingh
Last active October 16, 2017 22:55
Show Gist options
  • Save pravsingh/2bc3eabe79b49512dc1cc12970eb1da6 to your computer and use it in GitHub Desktop.
Save pravsingh/2bc3eabe79b49512dc1cc12970eb1da6 to your computer and use it in GitHub Desktop.
package com.designingmicroservices;
import java.util.Collection;
import java.util.Iterator;
/**
* Implements the Iterator on Collection of Collections.
*
* @author DesigningMicroservices.com
*
* @param <E>
*/
public class CollectionsIterator<E> implements Iterator<E> {
private Iterator<? extends Collection<E>> topIterator;
private Iterator<E> innerIterator;
private E next;
CollectionsIterator(Collection<? extends Collection<E>> collection) {
this.topIterator = collection.iterator();
prepareNext();
}
private void prepareNext() {
do {
if (innerIterator == null || !innerIterator.hasNext()) {
if (!topIterator.hasNext()) {
this.next = null;
return;
} else {
this.innerIterator = this.topIterator.next().iterator();
this.next = innerIterator.next();
}
} else {
this.next = innerIterator.next();
}
} while (next == null && topIterator.hasNext());
}
public boolean hasNext() {
return (next != null);
}
public E next() {
E previousNext = this.next;
prepareNext();
return previousNext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment