In Java ArrayList < String > convert a String [] |The Java Debug notes

This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Ask questions

How to convert an ArrayList

object to an array in String[]Java?

Top answers:

Answer 1:

List<String> list = .. ; String[] array = list.toArray(new String[0]);
Copy the code

Such as:

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
Copy the code

If no arguments are passed to toArray(), this method returns Object[]. Therefore, you must pass as an argument an array that will be filled with data from the list and returned. You can also pass an empty array, but you can also pass an array of the desired size.

Important update: The second line above used new String[list.size()]. However, this post shows that new String[0] is better due to JVM optimization.

Answer 2:

Methods in Java 8:

String[] strings = list.stream().toArray(String[]::new);
Copy the code

Java + 11:

String[] strings = list.toArray(String[]::new);
Copy the code

Answer 3:

You can use the toArray() method on a List:

ArrayList<String> list = new ArrayList<String>();

list.add("apple");
list.add("banana");

String[] array = list.toArray(new String[list.size()]);
Copy the code

Alternatively, you can manually add elements to the array:

ArrayList<String> list = new ArrayList<String>();

list.add("apple");
list.add("banana");

String[] array = new String[list.size()];

for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
}
Copy the code

Hope this helps!

Answer 4:

Starting with Java-11, the API** collection.toarray (IntFunction Generator)** can be used for the following purposes:

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
Copy the code

Answer 5:

ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray =  Arrays.copyOf(objectList,objectList.length,String[].class);
Copy the code

With copyOf, you can also perform an ArrayList operation on an array.

The original link