0

I want to convert List<List<Integer>> into the 2-D array in java. I am able to do that with the following code, but the problem my 2-d array uses primitive data type.

Integer[][] array = new Integer[resultList.size()][];
        for (i = 0; i < resultList.size(); i++) {
            ArrayList<Integer> row = (ArrayList<Integer>) resultList.get(i);
            array[i] = row.toArray(new Integer[row.size()]);
        }
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • ANKUR YADAV - If one of the answers resolved your issue, you can help the community by marking it as accepted. An accepted answer helps future visitors use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. – Arvind Kumar Avinash May 11 '20 at 14:30

2 Answers2

1

it sounds like you want a int[][] rather than a Integer[][]. in which case I would go with:

int[][] result = resultList.stream()                                
       .map(l -> l.stream().mapToInt(e -> e).toArray()) 
       .toArray(int[][]::new);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

You can do it by iterating List<List<Integer>> and copying elements of List<Integer> into the corresponding rows of int [][] array.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<List<Integer>> list = List.of(List.of(10, 20), List.of(5, 15));
        int[][] array = new int[list.size()][];
        for (int i = 0; i < list.size(); i++) {
            array[i] = new int[list.get(i).size()];
            for (int j = 0; j < list.get(i).size(); j++) {
                array[i][j] = list.get(i).get(j);
            }
        }

        // Display array[][]
        System.out.println(Arrays.deepToString(array));
    }
}

Output:

[[10, 20], [5, 15]]
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110