Search code examples
javajava-streamtostringcollect

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.


Solution

  • 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]