我如何在Java中转换ArrayList<String>对象为String[]数组?
当前回答
List<String> list = ..;
String[] array = list.toArray(new String[0]);
例如:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
不传递任何参数的toArray()方法返回Object[]。因此,您必须传递一个数组作为参数,该数组将由列表中的数据填充并返回。您也可以传递一个空数组,但也可以传递一个具有所需大小的数组。
重要更新:原来上面的代码使用了new String[list.size()]。然而,这篇博文揭示了由于JVM的优化,现在使用新的字符串[0]更好。
其他回答
从Java-11开始,可以使用API集合。toArray(IntFunction<T[]> generator)实现与:
List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
使用copyOf, ArrayList to array也可以实现。
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String [] strArry= list.stream().toArray(size -> new String[size]);
在每个评论中,我添加了一段话来解释转换是如何工作的。 首先,List被转换为String流。然后它使用Stream。toArray将流中的元素转换为数组。在上面的最后一个语句“size -> new String[size]”实际上是一个IntFunction函数,它分配一个String流大小的String数组。这句话与
IntFunction<String []> allocateFunc = size -> {
return new String[size];
};
String [] strArry= list.stream().toArray(allocateFunc);
如果需要对数据进行一些额外的操作,用户想要一个函数,这种方法并不完美(因为它需要将元素的类作为第二个参数传递),但有效:
进口java.util.ArrayList; 进口java.lang.reflect.Array;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
public static <T> T[] convert(ArrayList<T> al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}
Java 8中的替代方案:
String[] strings = list.stream().toArray(String[]::new);
Java 11 +:
String[] strings = list.toArray(String[]::new);