3

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
alejo
  • 317
  • 3
  • 10
  • `Arrays.stream(BOARD).map(Arrays::toString).map(row -> row.replace(" ", "")).collect(Collectors.joining("\n"))` – shmosel Nov 14 '18 at 03:39

3 Answers3

3

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);
shmosel
  • 49,289
  • 6
  • 73
  • 138
Naman
  • 27,789
  • 26
  • 218
  • 353
2

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]
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

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)));
Kartik
  • 7,677
  • 4
  • 28
  • 50