Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten nested arrays in java

I want to flatten nested arrays like:

[[[1],2],[3]],4] -> [1,2,3,4] 

manually in java I can't find a clue ! :S

I have tried a manual java script guide but it doesn't get a solution

like image 786
mhGaber Avatar asked Aug 06 '15 09:08

mhGaber


People also ask

How do you flatten nested arrays?

The array method accepts an optional parameter depth , which specifies how deep a nested array structure should be flattened (default to 1 ). So to flatten an array of arbitrary depth, just call flat method with Infinity .

What is flatten in Java?

Flattening is the process of converting several lists of lists and merge all those lists to create a single list containing all the elements from all the lists. Flattening Example. Consider the following lists of lists: Before Flattening: [[1, 2, 3, 4], [7, 8, 9, 0], [5, 6], [12, 18, 19, 20, 17], [22]]

How does flattening an array work?

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]]; and we need to return a new flat array with all the elements of the nested arrays in their original order.


1 Answers

Java 8’s Stream API offers a compact and flexible solution. Using the method

private static Stream<Object> flatten(Object[] array) {
    return Arrays.stream(array)
                 .flatMap(o -> o instanceof Object[]? flatten((Object[])o): Stream.of(o));
}

you can perform the operation as

Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10 };
System.out.println("original: "+Arrays.deepToString(array));

Object[] flat = flatten(array).toArray();
System.out.println("flat:     "+Arrays.toString(flat));

or when you assume the leaf objects to be of a specific type:

int[] flatInt = flatten(array).mapToInt(Integer.class::cast).toArray();
System.out.println("flat int: "+Arrays.toString(flat));
like image 58
Holger Avatar answered Sep 20 '22 23:09

Holger