overflowdb.util.IteratorUtils Maven / Gradle / Ivy
package overflowdb.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.function.Function;
import java.util.function.Predicate;
public class IteratorUtils {
public static ArrayList toArrayList(Iterator iterator) {
ArrayList list = new ArrayList<>();
while (iterator.hasNext()) {
list.add(iterator.next());
}
return list;
}
public static Iterator fromSingle(A a) {
return new SingleIterator<>(a);
}
public static Iterator from (A... as) {
return Arrays.stream(as).iterator();
}
public static final Iterator map(final Iterator iterator, final Function function) {
return new Iterator() {
public boolean hasNext() {
return iterator.hasNext();
}
public void remove() {
iterator.remove();
}
public E next() {
return function.apply(iterator.next());
}
};
}
public static final Iterator flatMap(final Iterator iterator, final Function> function) {
return new Iterator() {
private Iterator currentIterator = Collections.emptyIterator();
@Override
public boolean hasNext() {
if (this.currentIterator.hasNext()) {
return true;
} else {
while (iterator.hasNext()) {
this.currentIterator = function.apply(iterator.next());
if (this.currentIterator.hasNext())
return true;
}
}
return false;
}
@Override
public void remove() {
iterator.remove();
}
@Override
public E next() {
if (this.hasNext())
return this.currentIterator.next();
else
throw new NoSuchElementException();
}
};
}
public static final Iterator filter(final Iterator iterator, final Predicate predicate) {
return new Iterator() {
S nextResult = null;
@Override
public boolean hasNext() {
if (null != this.nextResult) {
return true;
} else {
advance();
return null != this.nextResult;
}
}
@Override
public void remove() {
iterator.remove();
}
@Override
public S next() {
try {
if (null != this.nextResult) {
return this.nextResult;
} else {
advance();
if (null != this.nextResult)
return this.nextResult;
else
throw new NoSuchElementException();
}
} finally {
this.nextResult = null;
}
}
private final void advance() {
this.nextResult = null;
while (iterator.hasNext()) {
final S s = iterator.next();
if (predicate.test(s)) {
this.nextResult = s;
return;
}
}
}
};
}
public static class SingleIterator implements Iterator {
private A element;
public SingleIterator(A element) {
this.element = element;
}
public boolean hasNext() {
return element != null;
}
public A next() {
A ret = element;
element = null; // free for garbage collection
return ret;
}
}
public static class ArrayIterator implements Iterator{
private final E[] elems;
private int pos;
public ArrayIterator(E[] elems){
this.elems = elems;
this.pos = 0;
}
public E next(){
return elems[pos++];
}
public boolean hasNext(){
return pos < elems.length;
}
}
}