com.unit16.z.Sequence Maven / Gradle / Ivy
package com.unit16.z;
import java.util.Iterator;
import java.util.function.Function;
import java.util.function.Predicate;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
/**
* Like {@link Iterator}, but immutable (and hence, simpler).
*/
public abstract class Sequence implements Iterable {
public abstract A next();
public abstract boolean hasNext();
public static Sequence fromIterator(final Iterator source)
{
return new Sequence(){
@Override
public B next() { return source.next(); }
@Override
public boolean hasNext() { return source.hasNext(); }
};
}
public static Sequence fromIterable(final Iterable source)
{
return fromIterator(source.iterator());
}
public final Sequence> zip(final Sequence snd)
{
final Sequence fst = this;
return new Sequence>(){
@Override
public Pair next() {
return new Pair.Const<>(fst.next(), snd.next());
}
@Override
public boolean hasNext() {
return fst.hasNext() && snd.hasNext();
}};
}
public final Sequence onResultOf(Function f)
{
return fromIterator(Iterators.transform(iterator(), x -> f.apply(x)));
}
public final Sequence filter(Predicate p)
{
return fromIterator(Iterators.filter(iterator(), x -> p.test(x)));
}
@Override
public final Iterator iterator()
{
return new UnmodifiableIterator() {
@Override
public boolean hasNext() { return Sequence.this.hasNext(); }
@Override
public A next() { return Sequence.this.next(); }
};
}
}