在Java中,我们可以使用将List
转换为数组,参考以下步骤:
- 循环(for / while / do-while)
- List.toArray()
- Stream(在Java8中引入)
文件:ListToArrayExample.java –
package com.yiibai.tutorial; import java.util.ArrayList; import java.util.List; /** * @author yiibai * */ public class ListToArrayExample { public static void main(String[] args) { //List to be converted into array List<String> list=new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.add("E"); /*Method - 1 (Using for loop)*/ String[] array1=new String[list.size()]; for (int i = 0; i < list.size(); i++) { array1[i]=list.get(i); } System.out.println("Method -1 Output:"); for (String string : array1) { System.out.println(string); } /*Method - 2 (List.toArray())*/ String[] array2=list.toArray(new String[list.size()]); System.out.println(" Method -2 Output:"); for (String string : array2) { System.out.println(string); } /*Method - 3 (Using stream)*/ String[] array3=list.stream().toArray(String[]::new); System.out.println(" Method -3 Output:"); for (String string : array3) { System.out.println(string); } } }
执行上面示例代码,得到以下结果 –
Method -1 Output: A B C D E Method -2 Output: A B C D E Method -3 Output: A B C D E
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264149.html