Home » Java » Convert List<String[]> to Object[][] 2d array in Java-Exceptionshub

Convert List<String[]> to Object[][] 2d array in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am trying to transform a List of string arrays to 2D object arrays Object[][].

Here is what I have so far. Is this correct?

private static Object[][] listToObject2dConvert(List<String[]> convertor) {
    Object[][] array = new Object[convertor.size()][];

    for (int i = 0; i < array.length; i++) {
        array[i] = new Object[convertor.get(i).length];
    }

    for (int i = 0; i < convertor.size(); i++){
        for (int j = 0; j < convertor.get(i).length; j++) {
            array[i][j] = convertor.get(i).length;
        }
    }
    return array;
}
How to&Answers:

The answer depends on whether you need to copy the contents out of the String[]s, or if it is acceptable to use those exact arrays.

If you can keep the exact arrays, it would be easiest to just do the following:

return convertor.toArray(Object[][]::new);

However, if you need to copy the values out of the array, you could use streams to easily solve it:

return converter.stream()
                .map(s -> Arrays.copyOf(s, s.length, Object[].class))
                .toArray(Object[][]::new);

Answer:

Try this.

    public static void main(String[] args) {
        List<String[]> convertor = 
              List.of(new String[]{"a","b","c"}, new String[]{"e","f","g"});
        Object[][] objs = listToObject2dConvert(convertor);
        for (Object[] o : objs) {
            System.out.println(Arrays.toString(o));
        }
    }
    // just assign the array that's in the List to the 2D array column entry.
    private static Object[][] listToObject2dConvert(List<String[]> convertor){
        Object[][] array= new Object[convertor.size()][];
        int i = 0;
        for (String[] s : convertor) {
            array[i++] = s;
        }
        return array;
    }