Java Convert ArrayList<String> to String[]
By:Roy.LiuLast updated:2019-08-11
In the old days, we can use list.toArray(new String[0]) to convert a ArrayList<String> into a String[]
StringArrayExample.java
package com.mkyong; import java.util.ArrayList; import java.util.List; public class StringArrayExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); // default, returns Object[], not what we want, // Object[] objects = list.toArray(); // all jdk String[] str = list.toArray(new String[0]); for (String s : str) { System.out.println(s);
Output
For Java 8, we can do like this :
// Java 8 String[] str = list.stream().toArray(String[]::new);
For Java 9, we have a new way to create a List
// Java 9 List<String> list = List.of("A", "B", "C");
For Java 11, we can do the conversion like this :
// Java 9 List<String> list = List.of("A", "B", "C"); // Java 11 String[] str = list.toArray(String[]::new);
From:一号门
Previous:Gson How to parse JSON
COMMENTS