com.softicar.platform.common.container.iterable.recurse.RecurseIterator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of platform-common Show documentation
Show all versions of platform-common Show documentation
The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.
package com.softicar.platform.common.container.iterable.recurse;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
public class RecurseIterator implements Iterator {
private final Iterator iterator;
private final Function> recurseFunction;
private Iterator subIterator;
public RecurseIterator(Iterable iterable, Function> recurseFunction) {
this(iterable.iterator(), recurseFunction);
}
public RecurseIterator(Iterator iterator, Function> recurseFunction) {
this.iterator = iterator;
this.recurseFunction = recurseFunction;
}
@Override
public boolean hasNext() {
if (subIterator != null && subIterator.hasNext()) {
return true;
}
return iterator.hasNext();
}
@Override
public T next() {
if (subIterator != null && subIterator.hasNext()) {
return subIterator.next();
}
if (iterator.hasNext()) {
T element = iterator.next();
Iterable subIterable = recurseFunction.apply(element);
this.subIterator = subIterable != null? new RecurseIterator<>(subIterable, recurseFunction) : null;
return element;
} else {
throw new NoSuchElementException();
}
}
}