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;
}
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);
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.