Flattening a 2D array to a 1D array based on indexes I am certain there is a better way to flatten the array with an optimized approach for the solution.

Example:


  [[1,2,24],[12,1241,122],[3,2],[7]] => 1 12 3 7 2 1241 2 24 122




public class flattenArray {

public static void main(String args[]) {

    int inputLists[][] = {{1,2,24},{12,1241,122},{3,2},{7}};

    flattenList(inputLists);

}

public static void flattenList(int input[][]){
    List result = new ArrayList();
    Map&lt;Integer, List&lt;Integer&gt;&gt; elements = new HashMap&lt;Integer,List&lt;Integer&gt;&gt;();
    for(int i=0;i&lt;input.length;i++){
        for(int j=0;j&lt;input[i].length;j++){

            List&lt;Integer&gt; temp = new ArrayList&lt;Integer&gt;();


            if(elements.get(j)!=null) {
                temp=elements.get(j);
                temp.add(input[i][j]);
                elements.put(j, temp);
            }

            else {
                temp.add(input[i][j]);
                elements.put(j,temp);
            }
        }
    }

    for(int i=0;i&lt;input.length;i++){
        if(elements.get(i)!=null)
        result.addAll(elements.get(i));
    }

    for(int i=0;i&lt;result.size();i++){
        System.out.println(result.get(i)+" ");
    }
}
}
Don't use raw types:

List result = new ArrayList();


Should be:

List&lt;Integer&gt; result = new ArrayList&lt;&gt;();


If you are using Java8, you could simplify the code of the map creation using the function computeIfAbsent:

for (int i = 0; i &lt; input.length; i++){
    for (int j = 0; j &lt; input[i].length; j++){
        elements.computeIfAbsent(j, k -&gt; new ArrayList&lt;&gt;()).add(input[i][j]);
    }
}


In the next loop, you are using the break condition incorrectly.

for(int i=0;i&lt;input.length;i++){ // input.length is not what you need 
    if(elements.get(i)!=null)
        result.addAll(elements.get(i));
}


input.length is the number of arrays in your 2d array. If the length of any array is greater than the number of arrays, the code is skipping values.

This is a failed test:

Input: {{1,2,24},{12,1241,122}} 
Output: 1 12 2 1241
Expected: 1 12 2 1241 24 122


You don't need to use input in the loop, you have a map with all the elements for each index, so you can make the conversion using only the map:

// Use a TreeMap instead of a HashMap to have the elements ordered by index
Map&lt;Integer, List&lt;Integer&gt;&gt; elements = new TreeMap&lt;Integer,List&lt;Integer&gt;&gt;();
...
for (List&lt;Integer&gt; e : elements.values()) {
    result.addAll(e);
}