Converting 'ArrayList<String> to 'String[]' in Java
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.
Alex
Updated on December 23, 2021Comments
-
Alex over 2 years
How might I convert an
ArrayList<String>
object to aString[]
array in Java?-
Naman almost 6 yearsHave made this answer with an updated approach with JDK-11 introducing a new an equally performant API to
toArray(T[])
and similar in syntax toStream.toArray
.
-
-
Alan Delimon over 11 yearsThis works, but isn't super efficient, and duplicates functionality in the accepted answer with extra code.
-
Adil Malik almost 11 yearsIt shows this warning in logcat: Converting to string: TypedValue{t=0x12/d=0x0 a=3 r=0x7f050009}
-
Jason Weden over 9 yearsSuggest camelcase so "objectList =..." and "stringArray". Also, it is Arrays.copyOf...capital O.
-
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 over 8 yearsTurns 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 over 8 yearsThis 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 about 8 yearsOr any benefits?
-
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 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 almost 8 yearsI would prefer that syntax, but IntelliJ displays a compiler error with that, complains "T[] is not a functional interface."
-
Udara Bentota over 7 years@GlenMazza you can only use
toArray
on aStream
object. This compilation error may occur if you reduce the stream using aCollectors
and then try to applytoArray
. -
David almost 7 yearslist.toArray() internally uses Arrays.copyOf()
-
Olivier Grégoire over 6 yearsI 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 incrementi
, and 4. thewhile
would be better off replaced by afor
. 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 over 6 yearsOkay, I got it now. Thanks.
-
Olivier Grégoire over 6 yearsWell, 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 over 6 yearsI am new here, so I don't know yet how things work here. Although, appreciate your help mate.
-
Olivier Grégoire over 6 yearsThis 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 over 6 years@Nyerguds Can you explain how java's fake generics disallow such function?
-
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. over 6 yearsWhy
parallelStream()
instead of simplystream()
? -
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 about 5 yearsWhat value does this answer add? It appears to just repeat other answers without explaining why it answers the question.
-
John Strood over 3 yearsI 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[]
, soString[list.size()]::new
? -
Unmitigated over 3 years@JohnStrood
String[]::new
is equivalent toi -> new String[i]
. See stackoverflow.com/questions/29447561/… -
John Strood over 3 years@iota Thank you! That makes more sense now.
-
Unmitigated over 3 years@JohnStrood No problem.
-
Alain BECKER almost 3 yearsIf generics has a meaning, wouldn't it rather be "convert any List<Type> to Type[]"?
-
Lluis Martinez about 2 yearsJava 20: String[] strings = list.toArray();
-
Simon Logic almost 2 yearsoutput type is wrong.