IntPipelineError in a nested loop
Paul Sandoz
paul.sandoz at oracle.com
Tue Apr 9 02:44:48 PDT 2013
Hi Jose,
You are consuming "sy" more than once. A stream is a "traversable once" thing, just like an iterator.
In your example you need to pass in "sy" as a supplier:
static void fold(IntStream sx, Supplier<IntStream> ssy, IntBiConsumer bc) {
sx.forEach(nx -> ssy.get().forEach(ny -> bc.accept(nx, ny)));
}
class Demo {
public static void main(String[] args) {
IntStream sx = Streams.intRange(0, 10);
Supplier<IntStream> ssy = () -> Streams.intRange(0, 5);
IntBiConsumer bc = (x, y) -> System.out.println("x: " + x + ", y: " + y);
fold(sx, ssy, bc);
}
}
Note your fold behaves more like a flatMap.
Paul.
On Apr 9, 2013, at 11:21 AM, Jose <jgetino at telefonica.net> wrote:
>
>
> Sorry if this issue has been commented before, but I coudn't find it in the
> archives.
>
> Tryng to use IntStream to emulate a nested loop, I get a IntPipelineError.
>
> The code is below:
>
> public interface IntBiConsumer {
> void accept(int n, int m);
>
> static void fold(IntStream sx, IntStream sy, IntBiConsumer bc) {
> sx.forEach(nx -> sy.forEach(ny -> bc.accept(nx, ny)));
> }
>
> class Demo {
> public static void main(String[] args) {
> IntStream sx = Streams.intRange(0, 10);
> IntStream sy = Streams.intRange(0, 5);
> IntBiConsumer bc = (x, y) -> System.out.println("x: " + x + ",
> y: " + y);
> fold(sx, sy, bc);
> }
> }
> }
>
>
More information about the lambda-dev
mailing list