How to convert nested list to array in Java

1 Answer

0 votes
import java.util.List;

public class NestedListToArray {
    public static void main(String[] args) {
        List<List<Integer>> nestedList = List.of(
            List.of(1, 2, 3, 0),
            List.of(4, 5, 6),
            List.of(7, 8, 9, 10, 11)
        );

        // Convert the nested list to a 2D array
        int[][] array = convertNestedListToArray(nestedList);

        for (int[] row : array) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }

    public static int[][] convertNestedListToArray(List<List<Integer>> nestedList) {
        // Determine the size of the outer list
        int rows = nestedList.size();
        // Initialize the 2D array
        int[][] array = new int[rows][];

        // Iterate over each inner list and convert it to an array
        for (int i = 0; i < rows; i++) {
            List<Integer> innerList = nestedList.get(i);
            array[i] = innerList.stream().mapToInt(Integer::intValue).toArray();
        }

        return array;
    }
}

 
 
/*
run:
 
1 2 3 0 
4 5 6 
7 8 9 10 11 
 
*/

 



answered Mar 31, 2025 by avibootz
...