Stream generators
Brian Goetz
brian.goetz at oracle.com
Fri Nov 30 09:51:04 PST 2012
> I think it would be beneficial for comparison to show a bit of their
> implementations.
Here's iterate(seed, UnaryOperator):
public static<T> Stream<T> iterate(final T seed, final
UnaryOperator<T> f) {
Objects.requireNonNull(f);
final InfiniteIterator<T> iterator = new InfiniteIterator<T>() {
T t = null;
@Override
public T next() {
return t = (t == null) ? seed : f.operate(t);
}
};
return stream(new StreamSource.ForIterator<>(iterator),
StreamOpFlag.IS_ORDERED);
}
Not too difficult. But, the idea is to make things that are easy in the
header of a for-loop to be easy as the source of a stream.
> repeat(n) in Scheme is about 10 characters.
Yeah, well this is Java...
> How difficult is it to implement a merge, as might be needed to generate
> Hamming numbers? (One of my favorite test cases.)
You mean, interleave two streams? That's on our list to implement as
Streams.interleave(a, b).
> Is there a method to limit a stream to a length? If so then one of your
> methods may be extra baggage.
Yes: stream.limit(n).
More information about the lambda-libs-spec-observers
mailing list