org.davidmoten.kool.internal.operators.stream.DoOnEmpty Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kool Show documentation
Show all versions of kool Show documentation
Streaming library supporting reuse and many operators
package org.davidmoten.kool.internal.operators.stream;
import java.util.NoSuchElementException;
import org.davidmoten.kool.Stream;
import org.davidmoten.kool.StreamIterator;
import org.davidmoten.kool.function.Action;
public final class DoOnEmpty implements Stream {
private final Stream stream;
private final Action action;
public DoOnEmpty(Stream stream, Action action) {
this.stream = stream;
this.action = action;
}
@Override
public StreamIterator iterator() {
return new StreamIterator() {
StreamIterator it = stream.iteratorNullChecked();
boolean checkedForEmpty;
@Override
public boolean hasNext() {
check();
return it.hasNext();
}
@Override
public T next() {
check();
if (it == null) {
throw new NoSuchElementException();
} else {
return it.nextNullChecked();
}
}
@Override
public void dispose() {
if (it != null) {
it.dispose();
// release for gc
it = null;
}
}
private void check() {
if (!checkedForEmpty) {
if (!it.hasNext()) {
action.callUnchecked();
}
checkedForEmpty = true;
}
}
};
}
}