fr.lirmm.graphik.util.stream.CloseableIteratorRecursive Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of integraal-graal-ruleset-analysis Show documentation
Show all versions of integraal-graal-ruleset-analysis Show documentation
Rule base analysis for InteGraal. This is imported from Graal
The newest version!
package fr.lirmm.graphik.util.stream;
import java.util.Stack;
/**
* This Iterator iterate recursively on Iterator or CloseableIterable results
* from a primary iterator.
*
* @author Olivier Rodriguez
*/
public class CloseableIteratorRecursive extends AbstractCloseableIterator {
private Stack> stackIterator;
private CloseableIterator currentIterator;
private E next;
// /////////////////////////////////////////////////////////////////////////
// CONSTRUCTOR
// /////////////////////////////////////////////////////////////////////////
public CloseableIteratorRecursive(CloseableIterator primaryIterator) {
stackIterator = new Stack<>();
currentIterator = primaryIterator;
}
// /////////////////////////////////////////////////////////////////////////
// METHODS
// /////////////////////////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
@Override
public boolean hasNext() throws IteratorException {
if (next != null)
return true;
if (currentIterator == null)
return false;
while (!currentIterator.hasNext()) {
currentIterator.close();
if (stackIterator.isEmpty()) {
currentIterator = null;
return false;
}
currentIterator = stackIterator.pop();
}
E next = currentIterator.next();
if (next instanceof CloseableIterator) {
stackIterator.push(currentIterator);
currentIterator = (CloseableIterator) next;
return currentIterator.hasNext();
} else if (next instanceof CloseableIterable) {
stackIterator.push(currentIterator);
currentIterator = ((CloseableIterable) next).iterator();
return currentIterator.hasNext();
}
this.next = next;
return true;
}
@Override
public E next() throws IteratorException {
if (next == null)
this.hasNext();
E ret = next;
next = null;
return ret;
}
@Override
public void close() {
if (currentIterator == null)
return;
currentIterator.close();
while (!stackIterator.isEmpty()) {
stackIterator.pop().close();
}
}
}