Last active
August 29, 2015 13:57
-
-
Save codyrioux/9437194 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
import java.util.Arrays; | |
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.lang.Iterable; | |
import java.util.NoSuchElementException; | |
import javax.naming.OperationNotSupportedException; | |
/** | |
* An iterator that flattens an iterator of iterators. | |
* | |
* Iterator SQUARED! | |
*/ | |
public class IteratorIterator<T> implements Iterator<T> { | |
private Iterator<Iterable<T>> _outerIterator; | |
private Iterator<T> _innerIterator; | |
@SafeVarargs | |
public <T> IteratorIterator(Iterable<T>... iterables) { | |
_outerIterator = Arrays.asList(iterables).iterator(); | |
_innerIterator = _outerIterator.next().iterator(); | |
} | |
@Override | |
public boolean hasNext() { | |
if (_innerIterator.hasNext()) { | |
return true; | |
} else { | |
while(_outerIterator.hasNext()) { | |
_innerIterator = _outerIterator.next().iterator(); | |
if (_innerIterator.hasNext()) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
@Override | |
public T next() { | |
if (_innerIterator.hasNext()) { | |
return _innerIterator.next(); | |
} else { | |
while(_outerIterator.hasNext()) { | |
_innerIterator = _outerIterator.next().iterator(); | |
if (_innerIterator.hasNext()) { | |
return _innerIterator.next(); | |
} | |
} | |
} | |
throw new NoSuchElementException(); | |
} | |
@Override | |
public void remove() { | |
// Ignore this function | |
try { | |
throw new OperationNotSupportedException("Don't worry about this one"); | |
} catch (OperationNotSupportedException e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* The below is meant to be a test case for your implementation above. If done correctly, | |
* it should print out the digits from 1 to 10, one per line, without any blank lines. | |
*/ | |
public static void main(String... args) { | |
List<Integer> a = Arrays.asList(new Integer[] {1 }); | |
List<Integer> b = Arrays.asList(new Integer[] {2, 3}); | |
List<Integer> c = Arrays.asList(new Integer[] { }); | |
List<Integer> d = Arrays.asList(new Integer[] { }); | |
List<Integer> e = Arrays.asList(new Integer[] {4}); | |
List<Integer> f = Arrays.asList(new Integer[] { }); | |
List<Integer> g = Arrays.asList(new Integer[] {5, 6, 7, 8, 9, 10}); | |
List<Integer> h = Arrays.asList(new Integer[] { }); | |
IteratorIterator<Integer> it = new IteratorIterator<Integer>(a, b, c, d, e, f, g, h); | |
while (it.hasNext()) { | |
System.out.println(it.next()); | |
} | |
System.out.println("Done!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment