Grouping stream elements by their position - how to handle tail of stream ?
Paul Sandoz
paul.sandoz at oracle.com
Mon Feb 4 04:58:57 PST 2013
Hi,
Just exploring ideas here... it's fun :-)
If your source is of some repeatable information one could do it as per the code below. Quite a mouthful! plus you have to be explicit about sequential or parallel.
If zip could take a third stream that acts as a pad one could avoid the concat:
Stream<Pair<A, A>> sz = Streams.zip(s1, s2, Stream.<A>generate(() -> null), Pair::new);
The zip code is not complex, i cheat and use iterators for an easy implementation, so it would also be easy to support padding.
My general point here is that it is sometimes possible to compose streams by composing the escape hatch spliterators/iterators of those streams. Obviously in some cases this is not as ideal as implementing an operation but it might be sufficient for some cases in the interim.
Paul.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import java.util.stream.Streams;
public class Test {
static class Pair<A, B> {
final A a;
final B b;
Pair(A a, B b) {
this.a = a;
this.b = b;
}
@Override
public String toString() {
return "[" + a + ", " + b + "]";
}
}
public static void main(String[] args) {
List<Integer> l = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> s1 = l.stream();
Stream<Integer> s2 = Streams.concat(l.stream().substream(1), Arrays.asList(new Integer[]{null}).stream());
Stream<Pair<Integer, Integer>> sz = Streams.zip(s1, s2, Pair::new);
sz.forEach(System.out::println);
}
}
On Feb 2, 2013, at 9:35 PM, Boaz Nahum <boaznahum at gmail.com> wrote:
> Hi.
>
> I looking in Stream interface for a way to convert a stream of
> { t1, t2, .. Tn }
> to
> { {t1,t2}, ... {Tn-1, Tn} }
> or
> { {t1,t2}, ... {Tn, null}}
>
> Lets assume {t1, t2} are aggeraget by Pair<T,T>
>
>
>
> So I tried to use explode:
>
> * Stream<Integer> si = Arrays.asList(1, 2, 3, 4, 5).stream();
>
> Stream<Pair<Integer, Integer>> spi = si.sequential().explode(new
> BiConsumer<Stream.Downstream<Pair<Integer, Integer>>, Integer>() {
>
> Integer firstValue;
>
> @Override
> public void accept(Stream.Downstream<Pair<Integer, Integer>>
> pairDownstream, Integer v) {
>
> if (firstValue == null) {
> firstValue = v;
> } else {
>
> pairDownstream.send(new Pair<>(firstValue, v));
> firstValue = null;
>
> }
> }
>
> });
> *
>
> But I didn't find a way to add the tail of input stream {.., 5} to the new
> stream { ,,, {5, null}}.
>
> Of-course this only simplified example of more general problem I have.
>
> Thanks
> Boaz
>
More information about the lambda-dev
mailing list