Alex
Alex

Reputation: 16675

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

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

Upvotes: 1294

Views: 982072

Answers (17)

Roberto Attias
Roberto Attias

Reputation: 1903

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

Upvotes: 5

Prasannjeet Singh
Prasannjeet Singh

Reputation: 1457

An alternate one-liner method for primitive types, such as double, int, etc.:

List<Double> coordList = List.of(3.141, 2.71);
double[] doubleArray = coordList.mapToDouble(Double::doubleValue).toArray();
List<Integer> coordList = List.of(11, 99);
int[] intArray = coordList.mapToInt(Integer::intValue).toArray();

and so on...

Upvotes: 0

Naman
Naman

Reputation: 32036

Starting from Java-11, one can 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

Upvotes: 63

nick w.
nick w.

Reputation: 159

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

Upvotes: 6

Vitalii Fedorenko
Vitalii Fedorenko

Reputation: 114550

An alternative in Java 8:

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

Java 11+:

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

Upvotes: 272

Rafal Borowiec
Rafal Borowiec

Reputation: 5254

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

Upvotes: 5

KayV
KayV

Reputation: 13855

In Java 8, it can be done using

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

Upvotes: 8

Panchal Nilkanth
Panchal Nilkanth

Reputation: 57

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

Upvotes: 2

Khaled Lela
Khaled Lela

Reputation: 8139

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

Upvotes: 6

Vatsal Chavda
Vatsal Chavda

Reputation: 149

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.

Upvotes: 7

Yoory N.
Yoory N.

Reputation: 5484

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.

Upvotes: 6

Denis Fedak
Denis Fedak

Reputation: 436

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

Upvotes: 1

Bozho
Bozho

Reputation: 597392

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

For example:

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

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.

Important update: Originally the code above used new String[list.size()]. However, this blogpost reveals that due to JVM optimizations, using new String[0] is better now.

Upvotes: 2097

Mike Shauneu
Mike Shauneu

Reputation: 3289

In Java 8:

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

Upvotes: 11

codecubed
codecubed

Reputation: 780

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!

Upvotes: 49

Rajesh Vemula
Rajesh Vemula

Reputation: 357

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.

Upvotes: 34

HZhang
HZhang

Reputation: 223

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

Upvotes: 5

Related Questions