StreamBuilder is awesome
Ali Lahijani
alahijani at gmail.com
Thu Apr 11 12:31:14 PDT 2013
I just want to express my delight at this great new feature.
StreamBuilder can be used to append to or concatenate Streams:
StreamBuilder<E> builder = Streams.builder();
s1.forEach(builder);
builder.accept(x);
builder.accept(y);
s2.forEach(builder);
Stream<E> stream = builder.build();
And it can be used to create streams fluently, and in push mode, which
is arguably the way that feels most natural in many situations.
StreamBuilder.OfInt builder = Streams.intBuilder();
for (int i = 0; i < 1000; i++) {
if (isPrime(i)) {
build.accept(i)
}
}
IntStream stream = builder.build();
Though admittedly, streams built this way might benefit much from
Stream framework's support for parallelism.
An observation:
The call to build() at the end should always be put there, and exactly
once. After that point, the builder should no longer be used. In line
with these rules, I would prefer the following syntax:
Stream<E> Streams.build((builder) -> {
s1.forEach(builder);
builder.accept(x);
builder.accept(y);
s2.forEach(builder);
});
The implicit call to build() is inserted after the lambda returns,
after which point the builder is no longer available to be used. I
think it feels more natural, and a bit more Lambda-like.
Once again, thanks for giving us this great new tool!
Best
More information about the lambda-dev
mailing list