How might I convert an ArrayList
object to a String[]
array in Java?
In Java 8:
String[] strings = list.parallelStream().toArray(String[]::new);
Generics solution to covert any List<Type>
to String []
:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Note You must override toString()
method.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
You can use Iterator<String>
to iterate the elements of the ArrayList<String>
:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Now you can retrive elements from String[]
using any Loop.
In Java 11, we can use the Collection.toArray(generator)
method. The following code will create a new array of strings:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
from java.base's java.util.Collection.toArray().
An alternative in Java 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
You can convert List to String array by using this method:
Object[] stringlist=list.toArray();
The complete example:
ArrayList<String> list=new ArrayList<>();
list.add("Abc");
list.add("xyz");
Object[] stringlist=list.toArray();
for(int i = 0; i < stringlist.length ; i++)
{
Log.wtf("list data:",(String)stringlist[i]);
}