Last active
October 16, 2017 22:55
-
-
Save pravsingh/2bc3eabe79b49512dc1cc12970eb1da6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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