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

840,556

Solution 1

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.

Solution 2

An alternative in Java 8:

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

Java 11+:

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

Solution 3

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!

Solution 4

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

Solution 5

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.

Share:
840,556
Alex
Author by

Alex

Updated on December 23, 2021

Comments

  • Alex
    Alex over 2 years

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

    • Naman
      Naman almost 6 years
      Have made this answer with an updated approach with JDK-11 introducing a new an equally performant API to toArray(T[]) and similar in syntax to Stream.toArray.
  • Alan Delimon
    Alan Delimon over 11 years
    This works, but isn't super efficient, and duplicates functionality in the accepted answer with extra code.
  • Adil Malik
    Adil Malik almost 11 years
    It shows this warning in logcat: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f050009}
  • Jason Weden
    Jason Weden over 9 years
    Suggest camelcase so "objectList =..." and "stringArray". Also, it is Arrays.copyOf...capital O.
  • sferencik
    sferencik over 8 years
    @ThorbjørnRavnAndersen: the size of the array doesn't make any difference functionally but if you pass it in with the right size, you save the JVM the work of resizing it.
  • Stuart Marks
    Stuart Marks over 8 years
    Turns out that providing a zero-length array, even creating it and throwing it away, is on average faster than allocating an array of the right size. For benchmarks and explanation see here: shipilev.net/blog/2016/arrays-wisdom-ancients
  • River
    River over 8 years
    This is really already contained in this answer. Perhaps add it as an edit to that answer instead of as an entirely new one.
  • James Watkins
    James Watkins about 8 years
    Or any benefits?
  • Powerlord
    Powerlord about 8 years
    @StuartMarks It irks me that was only tested on Sun JVMs. There's no guarantee it will be faster on other systems such as ART (Android runtime) or IBM's JVM, which is used a lot on servers.
  • Stuart Marks
    Stuart Marks about 8 years
    @Powerlord I'm sorry that it irks you. Perhaps you could run some tests on these platforms and report the results. I think many people would find them interesting.
  • Glen Mazza
    Glen Mazza almost 8 years
    I would prefer that syntax, but IntelliJ displays a compiler error with that, complains "T[] is not a functional interface."
  • Udara Bentota
    Udara Bentota over 7 years
    @GlenMazza you can only use toArray on a Stream object. This compilation error may occur if you reduce the stream using a Collectors and then try to apply toArray.
  • David
    David almost 7 years
    list.toArray() internally uses Arrays.copyOf()
  • Olivier Grégoire
    Olivier Grégoire over 6 years
    I downvoted because: 1. no use of generics which force you into 2. using .toString() where no explicit cast would be needed, 3. you don't even increment i, and 4. the while would be better off replaced by a for. Suggested code: ArrayList<String> stringList = ... ; String[] stringArray = new String[stringList.size()]; int i = 0; for(Iterator<String> it = stringList.iterator(); it.hasNext(); i++) { stringArray[i] = it.next(); }
  • Vatsal Chavda
    Vatsal Chavda over 6 years
    Okay, I got it now. Thanks.
  • Olivier Grégoire
    Olivier Grégoire over 6 years
    Well, ideally, you should edit your code to include those comments (that is... if you think they're good for your answer!). I won't consider removing my downvote while the code remains unchanged.
  • Vatsal Chavda
    Vatsal Chavda over 6 years
    I am new here, so I don't know yet how things work here. Although, appreciate your help mate.
  • Olivier Grégoire
    Olivier Grégoire over 6 years
    This is much better! I've edited just a bit, but you've just experienced how it works: provide answer, improve them, get the laurels ;)
  • Lyuboslav
    Lyuboslav over 6 years
    @Nyerguds Can you explain how java's fake generics disallow such function?
  • Nyerguds
    Nyerguds over 6 years
    @lyuboslavkanev The problem is that having the generic type in Java isn't enough to actually create objects based on that type; not even an array (which is ridiculous, because that should work for any type). All that can be done with it, as far as I can see, is casting. In fact, to even create objects of the type, you need to have the actual Class object, which seems to be completely impossible to derive from the generic type. The reason for this, as I said, is that the whole construction is fake; it's all just stored as Object internally.
  • Yoory N.
    Yoory N. over 6 years
    Why parallelStream() instead of simply stream()?
  • jsears
    jsears about 6 years
    @Bozho From that article you like to: Bottom line: toArray(new T[0]) seems faster, safer, and contractually cleaner, and therefore should be the default choice now. Future VM optimizations may close this performance gap for toArray(new T[size]), rendering the current "believed to be optimal" usages on par with an actually optimal one. Further improvements in toArray APIs would follow the same logic as toArray(new T[0]) — the collection itself should create the appropriate storage.
  • Richard
    Richard about 5 years
    What value does this answer add? It appears to just repeat other answers without explaining why it answers the question.
  • John Strood
    John Strood over 3 years
    I don't get it. String[]::new is equivalent to () -> new String[]. But the given interface method expects an integer. Shouldn't it be (list.size()) -> new String[], so String[list.size()]::new ?
  • Unmitigated
    Unmitigated over 3 years
    @JohnStrood String[]::new is equivalent to i -> new String[i]. See stackoverflow.com/questions/29447561/…
  • John Strood
    John Strood over 3 years
    @iota Thank you! That makes more sense now.
  • Unmitigated
    Unmitigated over 3 years
    @JohnStrood No problem.
  • Alain BECKER
    Alain BECKER almost 3 years
    If generics has a meaning, wouldn't it rather be "convert any List<Type> to Type[]"?
  • Lluis Martinez
    Lluis Martinez about 2 years
    Java 20: String[] strings = list.toArray();
  • Simon Logic
    Simon Logic almost 2 years
    output type is wrong.