alejo
alejo

Reputation: 307

Formatting a 2d int array into a string using streams

I have the following array:

private static final int[][] BOARD = {
    { 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0 }
};

And I want to create a String representation on it, so if I were to print it on the console, it should look like this:

[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]

I can get this done with 2 nested for loops, but I am trying to accomplish this using streams. This is what I got so far:

public String toString() {
    StringJoiner board = new StringJoiner("\n");

    for (int i = 0; i < BOARD.length; i++) {
        board.add(
            IntStream.of(BOARD[i])
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(",", "[", "]"))
        );
    }
    return board.toString();
}

Is this something possible? I'm not particularly interested in performance (feel free to add some comments on that regard if you want), I am just trying to do this in a single chain of stream operations.

Upvotes: 3

Views: 100

Answers (3)

Kartik
Kartik

Reputation: 7917

Collections' toString() already provides that notation in the AbstractCollection class. Just use:-

Arrays.stream(BOARD)
        .forEach(ints -> System.out.println(
                Arrays.stream(ints).boxed().collect(Collectors.toList()))
        );

Or if you are happy to change int[][] to Integer[][], you can even do:-

Arrays.stream(BOARD)
        .forEach(ints -> System.out.println(Arrays.deepToString(ints)));

Upvotes: 0

Naman
Naman

Reputation: 32008

You can alternatively do it using Arrays.streamas :

Arrays.stream(BOARD)
        .map(aBOARD -> IntStream.of(aBOARD)
                .mapToObj(String::valueOf)
                .collect(Collectors.joining(",", "[", "]")))
        .forEach(board::add);

Upvotes: 3

Elliott Frisch
Elliott Frisch

Reputation: 201497

You can nest the stream and map each level together, first by commas and then by the system line separator. Like,

return Arrays.stream(BOARD).map(a -> Arrays.stream(a)
            .mapToObj(String::valueOf).collect(Collectors.joining(",", "[", "]")))
            .collect(Collectors.joining(System.lineSeparator()));

I get

[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]
[0,0,0,0,0]

Upvotes: 2

Related Questions