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.

1
  • Arrays.stream(BOARD).map(Arrays::toString).map(row -> row.replace(" ", "")).collect(Collectors.joining("\n")) Commented Nov 14, 2018 at 3:39

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

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

Comments

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.