user1738539
user1738539

Reputation: 941

Java 8 Stream Nested for loop

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)));

Upvotes: 2

Views: 3162

Answers (1)

Andreas
Andreas

Reputation: 159215

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;
    }
}

Upvotes: 4

Related Questions