Friday, January 22, 2016

How to convert ArrayList containing Strings to an array of Strings in Java?

ArrayList to array Conversion


How might I convert an ArrayList<String> object to a String[] array in Java?

List<String> list = ..;
String[] array = list.toArray(new String[list.size()]);
For example:
List<String> list =new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[list.size()]);
The toArray() method without passing any argument returns Object[]. So you have to pass an array as an argument, which will be filled with the data from the list, and returned. You can pass an empty array as well, but you can also pass an array with the desired size.

Java 8 implements:

An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);

No comments:

Post a Comment