package bjc.data; import java.util.*; import java.util.function.Function; /** * Create an iterator that applies a flat-map function * * @author bjcul * * @param The source type * @param The output type * */ public class FlatMapIterator implements Iterator { private Function> action; private Iterator source; private Iterator output; /** * Create a new flat-map iterator * * @param source The source iterator * @param action The action to apply to the iterator */ public FlatMapIterator(Iterator source, Function> action) { this.source = source; this.action = action; } @Override public boolean hasNext() { if (output != null && output.hasNext()) return true; while (source.hasNext()) { output = action.apply(source.next()); if (output.hasNext()) return true; } return false; } @Override public T2 next() { if (output != null && output.hasNext()) return output.next(); while (source.hasNext()) { output = action.apply(source.next()); if (output.hasNext()) return output.next(); } throw new NoSuchElementException(); } }