2

How can I do the following nested loop using java stream?

for (int x = 0; x < 5; x++) {
    for (int y = 0; y < 5; y++) {
        System.out.println(x + ", " + y);
    }   
}

I can easily do one loop with IntStream.range(0, 5). Is this possible with streams?

EDIT: well I guess I can do this, but can it be done with flatMap?

IntStream.range(0, 5)
         .forEach(x -> IntStream.range(x, 5).forEach(y -> System.out.println(x + ", " + y)));
2
  • 3
    Is there any reason for using a stream? You do not have to migrate every loop to a stream operation just because you can. Commented Dec 29, 2016 at 21:08
  • 1
    I prefer your version over using flatMap. But I prefer two loops over any stream version. Commented Dec 29, 2016 at 21:32

1 Answer 1

4

Do you mean something like this?

IntStream.range(0, 5)
         .boxed()
         .flatMap(x -> IntStream.range(0, 5)
                                .mapToObj(y -> new int[] { x, y }))
         .map(xy -> xy[0] + ", " + xy[1])
         .forEach(System.out::println);

UPDATE

It would be better if the array is replaced with an actual object.

IntStream.range(0, 5)
         .boxed()
         .flatMap(x -> IntStream.range(0, 5)
                                .mapToObj(y -> new Coord(x, y)))
         .forEach(System.out::println);
public final class Coord {
    private final int x;
    private final int y;
    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return this.x;
    }
    public int getY() {
        return this.y;
    }
    @Override
    public String toString() {
        return this.x + ", " + this.y;
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes just like that. I couldn't figure out how to use flatMap() to create the tuple x,y
Too bad you cannot lift pairing function like comma into a pair of list monands in Java8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.