Created
May 15, 2017 21:42
-
-
Save deyindra/b4847daebcc2d30e1ca4a927174a9966 to your computer and use it in GitHub Desktop.
Unfolded Iterator
This file contains hidden or 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
public class FlattentNestedIterator<T> implements Iterator<T>{ | |
private Stack<Iterator<Nested<T>>> stack = new Stack<>(); | |
private T current; | |
private boolean hasNext; | |
public FlattentNestedIterator(Iterator<Nested<T>> nestedIterator) { | |
if(nestedIterator == null){ | |
throw new IllegalArgumentException("Invalid Iterator"); | |
} | |
stack.push(nestedIterator); | |
advance(); | |
} | |
@Override | |
public boolean hasNext() { | |
return hasNext; | |
} | |
private void advance(){ | |
while(!stack.isEmpty()){ | |
Iterator<Nested<T>> top = stack.peek(); | |
if(top==null || !top.hasNext()){ | |
stack.pop(); | |
}else{ | |
Nested<T> n = top.next(); | |
if (n.isObject()) { | |
current = n.getObject(); | |
hasNext = true; | |
return; | |
} else { | |
stack.push(n.getIterator()); | |
} | |
} | |
} | |
hasNext =false; | |
} | |
@Override | |
public T next() { | |
if(!hasNext()){ | |
throw new NoSuchElementException(); | |
} | |
T result = current; | |
advance(); | |
return result; | |
} | |
} |
This file contains hidden or 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
public class Nested<T> { | |
private T object; | |
private Iterator<Nested<T>> iterator; | |
private boolean isObject; | |
private Nested(T object, Iterator<Nested<T>> iterator, boolean isObject) { | |
this.object = object; | |
this.iterator = iterator; | |
this.isObject = isObject; | |
} | |
public T getObject() { | |
return object; | |
} | |
public Iterator<Nested<T>> getIterator() { | |
return iterator; | |
} | |
public boolean isObject() { | |
return isObject; | |
} | |
public static class NestedBuiler<T>{ | |
public Nested<T> withObject(T object){ | |
return new Nested<>(object, null, true); | |
} | |
public Nested<T> withIterator(Iterator<Nested<T>> iterator){ | |
return new Nested<>(null, iterator, false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment