0

I'm trying to convert a two dimensional int array to a single int where there is a space in between each number and a line break after each single array using streams.

I've done this easily for single dimensional arrays with mapToObj, but this does not when the stream consists of arrays instead of ints.

int[] a = {1, 2, 3, 4};

String[] strArray = Arrays.stream(a).mapToObj(String::valueOf).toArray(String[]::new);

String joined = String.join(" ", strArray);

a would map to 1 2 3 4 here. What I want would be to have something like

int[][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

map to

1 2 3
4 5 6 
7 8 9

How can I get something similar to joined, but with two dimensional arrays and still using streams?

2
  • 1
    Can you please show what the output is supposed to look like for a given input? Commented Jul 6, 2019 at 19:55
  • 1
    Sorry about that, fixed! Commented Jul 6, 2019 at 20:02

1 Answer 1

6

You can use something like this :

 String output = Arrays.stream(a)
                .map(ints -> IntStream.of(ints).mapToObj(String::valueOf).collect(Collectors.joining(" ")))
                .collect(Collectors.joining("\n"));

The output will be :

1 2 3
4 5 6
7 8 9

First we map every integer array to a String which consists of integers separated by space and then we collect those Strings joining them with "\n".

Sign up to request clarification or add additional context in comments.

1 Comment

You can also skip the assignment to output and replace the last joining with forEach(System.out::println). Either way, very nicely done!

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.