[java] Converting 'ArrayList<String> to 'String[]' in Java

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

This question is related to java arrays string arraylist collections

The answer is


List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
  array[i++] = s;
}

In Java 8:

String[] strings = list.parallelStream().toArray(String[]::new);

We have following three ways for converting arraylist to array

  1. public T[] toArray(T[] a) - In this way we will create a array with size of list then put in method as String[] arr = new String[list.size()];

    arr = list.toArray(arr);

  2. Public get() method - In this way we iterate list and put element in array one by one

Reference : How to convert ArrayList To Array In Java


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().


    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    String [] strArry= list.stream().toArray(size -> new String[size]);

Per comments, I have added a paragraph to explain how the conversion works. First, List is converted to a String stream. Then it uses Stream.toArray to convert the elements in the stream to an Array. In the last statement above "size -> new String[size]" is actually an IntFunction function that allocates a String array with the size of the String stream. The statement is identical to

IntFunction<String []> allocateFunc = size -> { 
return new String[size];
};   
String [] strArry= list.stream().toArray(allocateFunc);

If your application is already using Apache Commons lib, you can slightly modify the accepted answer to not create a new empty array each time:

List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);

// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);

There are a few more preallocated empty arrays of different types in ArrayUtils.

Also we can trick JVM to create en empty array for us this way:

String[] array = list.toArray(ArrayUtils.toArray());

// or if using static import
String[] array = list.toArray(toArray());

But there's really no advantage this way, just a matter of taste, IMO.


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

Using copyOf, ArrayList to arrays might be done also.


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]);
    }

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.


private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
    String[] delivery = new String[deliveryServices.size()];
    for (int i = 0; i < deliveryServices.size(); i++) {
        delivery[i] = deliveryServices.get(i).getName();
    }
    return delivery;
}

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);

In Java 8, it can be done using

String[] arrayFromList = fromlist.stream().toArray(String[]::new);

You can use the toArray() method for List:

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

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

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

Or you can manually add the elements to an 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);
}

Hope this helps!


An alternative in Java 8:

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

Java 11+:

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

in case some extra manipulation of the data is desired, for which the user wants a function, this approach is not perfect (as it requires passing the class of the element as second parameter), but works:

import java.util.ArrayList; import java.lang.reflect.Array;

public class Test {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<>();
    al.add(1);
    al.add(2);
    Integer[] arr = convert(al, Integer.class);
    for (int i=0; i<arr.length; i++)
      System.out.println(arr[i]);
  }

  public static <T> T[] convert(ArrayList<T> al, Class clazz) {
    return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
  }
}

Starting from Java-11, one can alternatively use the API Collection.toArray(IntFunction<T[]> generator) to achieve the same as:

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

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to collections

Kotlin's List missing "add", "remove", Map missing "put", etc? How to unset (remove) a collection element after fetching it? How can I get a List from some class properties with Java 8 Stream? Java 8 stream map to list of keys sorted by values How to convert String into Hashmap in java How can I turn a List of Lists into a List in Java 8? MongoDB Show all contents from all collections Get nth character of a string in Swift programming language Java 8 Distinct by property Is there a typescript List<> and/or Map<> class/library?