Skip to content

Instantly share code, notes, and snippets.

@Miha-x64
Created May 8, 2021 20:32
Show Gist options
  • Save Miha-x64/480c50b780a3a7b0746abb27e4af355c to your computer and use it in GitHub Desktop.
Save Miha-x64/480c50b780a3a7b0746abb27e4af355c to your computer and use it in GitHub Desktop.
package net.aquadc.util;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.Stream;
public final class Iterators {
private Iterators() {}
public static <T> Iterator<T> ofStream(Stream<? extends T> stream) {
return new AutoCloseIterator<T>(stream.iterator(), stream);
}
private static final class AutoCloseIterator<T> implements Iterator<T> {
private final Iterator<? extends T> iterator;
private final AutoCloseable closeable;
private AutoCloseIterator(Iterator<? extends T> iterator, AutoCloseable closeable) {
this.iterator = iterator;
this.closeable = closeable;
}
@Override public boolean hasNext() {
return iterator.hasNext();
}
@Override public T next() {
T next = iterator.next();
if (!iterator.hasNext()) close();
return next;
}
@Override public void remove() {
iterator.remove();
}
@Override public void forEachRemaining(Consumer<? super T> action) {
iterator.forEachRemaining(action);
close();
}
private void close() {
try { closeable.close(); }
catch (IOException e) { throw new UncheckedIOException(e); }
catch (RuntimeException e) { throw e; }
catch (Exception e) { throw new RuntimeException(e); }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment