0

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;
}
1
  • Why don't you just run this piece of code and after that print the result instead of asking the community is this code correct. If you are looking better solution as given in the answers you have to ask about it, but not ask about verification. We are not a compilator;) Commented Feb 19, 2020 at 17:45

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Both are nice solutions and I would prefer the first. But depending on the nature of the question and questioner I tend to focus on more vanilla approaches.
1

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;
    }

1 Comment

Thanks a lot WJS!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.