Using Collection.toArray method
First way to convert arraylist is to use built-in for every java collection method toArray(T[] ts)
For example:
1 2 3 4 5 6 |
List<String> animals = new ArrayList<String>(); //add some elements animals.add("cat"); animals.add("dog"); String[] stringArray = animals.toArray(new String[0]); System.out.println(Arrays.toString(stringArray)); |
The toArray() method without any argument returns Object[]. So you have to pass an array as an argument to use method toArray(T[] ts) . This array 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.
Important note: Originally the code above used new String[list.size()] . But this blogpost reveals that due to JVM optimizations, using new String[0] is better.
Using Java 8 stream api
An alternative ways to convert arraylist is to use new Stream API available in Java 8:
1 |
String[] strings = animals.stream().toArray(String[]::new); |