Stream generators
Paul Sandoz
paul.sandoz at oracle.com
Fri Nov 30 11:13:46 PST 2012
On Nov 30, 2012, at 6:41 PM, Joe Bowbeer <joe.bowbeer at gmail.com> wrote:
> My first impression is that there are a lot. Whether they carry their
> weight depends on how difficult it is to implement these directly.
>
The following:
<T> Stream<T> repeat(T t)
<T> Stream<T> repeat(int n, T t)
<T> Stream<T> repeatedly(Supplier<T> f)
all defer to:
public static<T> Stream<T> repeatedly(final int n, final Supplier<T> f) {
Objects.requireNonNull(f);
if (n < 0) {
InfiniteIterator<T> iterator = () -> f.get();
return stream(new StreamSource.ForIterator<>(iterator), StreamOpFlag.IS_ORDERED);
}
else {
final Iterator<T> repeatedly = new Iterator<T>() {
int c = n;
@Override
public boolean hasNext() {
return c > 0;
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
c--;
return f.get();
}
};
return stream(new StreamSource.ForIterator<>(repeatedly), StreamOpFlag.IS_ORDERED);
}
}
Paul.
More information about the lambda-libs-spec-observers
mailing list