OneCompiler

[Java] How to flatten array of arrays?

I want to create an array of single dimension from the multi dimension arrays, how can I do that in Java?

1 Answer

4 years ago by

We can use flatMap on streams to achieve this. Following code snippet shows how to do that.

Stream<Object> flatten(Object[] array) {
return Arrays.stream(inpArray)
    .flatMap(ele -> e;e instanceof Object[]? flatten((Object[])ele): Stream.of(ele));
}    
4 years ago by Karthik Divi