1

I'm trying to use streams to flatten a multidimensional string array. I could do it with loops but streams seems to be the more idiomatic way. I'm aware of this question but that uses integer specific methods. The following returns an object array instead of the expected String[].

String[][][] sources = new String[][][]{
           {{"a","b","c"},{"d","e","f"}}
           {{"g","h","i"},{"j","k","l"}}
};
String[] values = Arrays.stream(sources[0])
            .flatMap(Arrays::stream)
            .toArray();
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
A. Scientist
  • 52
  • 1
  • 11

1 Answers1

4

To make your current example compile, the toArray should be:

String[] values = Arrays.stream(sources[0])
                        .flatMap(Arrays::stream)
                        .toArray(String[]::new); // <----------------------

If you want to do it for sources you'll need to use flatMap twice then collect to an array with .toArray(String[]::new):

String[] values = Arrays.stream(sources)
                        .flatMap(Arrays::stream)
                        .flatMap(Arrays::stream)
                        .toArray(String[]::new);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126