With streams added in Java 8 we can write code like:

int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();

Thought process:

  • The simple Stream#toArray returns an Object[] array, so it is not what we want. Also, Stream#toArray(IntFunction<A[]> generator) which returns A[] doesn't do what we want, because the generic type A can't represent the primitive type int

  • So it would be nice to have some kind of stream which would be designed to handle primitive type int instead of the reference type like Integer, because its toArray method will most likely also return an int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural for int). And fortunately Java 8 has such a stream which is IntStream

  • So now the only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream()) to that shiny IntStream.

    Quick searching in documentation of Stream while looking for methods which return IntStream points us to our solution which is mapToInt(ToIntFunction<? super T> mapper) method. All we need to do is provide a mapping from Integer to int.

    Since ToIntFunction is functional interface we can also provide its instance via lambda or method reference.

    Anyway to convert Integer to int we can use Integer#intValue so inside mapToInt we can write:

    mapToInt( (Integer i) -> i.intValue() )
    

    (or some may prefer: mapToInt(Integer::intValue).)

    But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type int (the lambda used in mapToInt is an implementation of the ToIntFunction interface which expects as body a method of type: int applyAsInt(T value) which is expected to return an int).

    So we can simply write:

    mapToInt((Integer i)->i)
    

    Also, since the Integer type in (Integer i) can be inferred by the compiler because List<Integer>#stream() returns a Stream<Integer>, we can also skip it which leaves us with

    mapToInt(i -> i)
    
Answer from Pshemo on Stack Overflow
🌐
W3Schools
w3schools.com › java › ref_arraylist_toarray.asp
Java ArrayList toArray() Method
(); cars.add("Volvo"); cars.add("BMW"); ... : carsArray) { System.out.println(item); } } } ... The toArray() method returns an array containing all of the items in the list....
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-toarray-method-in-java-with-examples
ArrayList toArray() method in Java with Examples - GeeksforGeeks
Then, the toArray() method is called to obtain an array representation of the ArrayList's elements, which is printed using Arrays.toString(arr). This Java program demonstrates how to convert an ArrayList of integers into an array of the integers using the toArray(T[]) method...
Published   December 19, 2018
Top answer
1 of 16
1073

With streams added in Java 8 we can write code like:

int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();

Thought process:

  • The simple Stream#toArray returns an Object[] array, so it is not what we want. Also, Stream#toArray(IntFunction<A[]> generator) which returns A[] doesn't do what we want, because the generic type A can't represent the primitive type int

  • So it would be nice to have some kind of stream which would be designed to handle primitive type int instead of the reference type like Integer, because its toArray method will most likely also return an int[] array (returning something else like Object[] or even boxed Integer[] would be unnatural for int). And fortunately Java 8 has such a stream which is IntStream

  • So now the only thing we need to figure out is how to convert our Stream<Integer> (which will be returned from list.stream()) to that shiny IntStream.

    Quick searching in documentation of Stream while looking for methods which return IntStream points us to our solution which is mapToInt(ToIntFunction<? super T> mapper) method. All we need to do is provide a mapping from Integer to int.

    Since ToIntFunction is functional interface we can also provide its instance via lambda or method reference.

    Anyway to convert Integer to int we can use Integer#intValue so inside mapToInt we can write:

    mapToInt( (Integer i) -> i.intValue() )
    

    (or some may prefer: mapToInt(Integer::intValue).)

    But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type int (the lambda used in mapToInt is an implementation of the ToIntFunction interface which expects as body a method of type: int applyAsInt(T value) which is expected to return an int).

    So we can simply write:

    mapToInt((Integer i)->i)
    

    Also, since the Integer type in (Integer i) can be inferred by the compiler because List<Integer>#stream() returns a Stream<Integer>, we can also skip it which leaves us with

    mapToInt(i -> i)
    
2 of 16
265

Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:

  • List<T>.toArray won't work because there's no conversion from Integer to int
  • You can't use int as a type argument for generics, so it would have to be an int-specific method (or one which used reflection to do nasty trickery).

I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(

Even though the Arrays class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).

🌐
Javatpoint
javatpoint.com › java-list-toarray-method
Java List toArray() Method with Examples - Javatpoint
The toArray() method of List interface returns an array containing all the elements present in the list in proper order · The second syntax returns an array containing all of the elements in this list where the runtime type of the returned array is that of the specified array
Top answer
1 of 11
1513

Either:

Foo[] array = list.toArray(new Foo[0]);

or:

Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);

Update:

It is recommended now to use list.toArray(new Foo[0]);, not list.toArray(new Foo[list.size()]);.

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

2 of 11
408

An alternative in Java 8:

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

Since Java 11:

String[] strings = list.toArray(String[]::new);
Top answer
1 of 8
60

From the javadocs:

Like the toArray() method, this method acts as bridge between array-based and collection-based APIs. Further, this method allows precise control over the runtime type of the output array, and may, under certain circumstances, be used to save allocation costs.

This means that the programmer is in control over what type of array it should be.

For example, for your ArrayList<Integer> instead of an Integer[] array you might want a Number[] or Object[] array.

Furthermore, the method also checks the array that is passed in. If you pass in an array that has enough space for all elements, the the toArray method re-uses that array. This means:

Integer[] myArray = new Integer[myList.size()];
myList.toArray(myArray);

or

Integer[] myArray = myList.toArray(new Integer[myList.size()]);

has the same effect as

Integer[] myArray = myList.toArray(new Integer[0]);

Note, in older versions of Java the latter operation used reflection to check the array type and then dynamically construct an array of the right type. By passing in a correctly sized array in the first place, reflection did not have to be used to allocate a new array inside the toArray method. That is no longer the case, and both versions can be used interchangeably.

2 of 8
9

It is declared generically so that you can write code such as

Integer[] intArray = list.toArray(new Integer[0]);

without casting the array coming back.

It is declared with the following annotation:

@SuppressWarnings("unchecked")

In other words, Java is trusting you to pass in an array parameter of the same type, so your error does not occur.

🌐
Tabnine
tabnine.com › home page › code › java › java.util.list
java.util.List.toArray java code examples | Tabnine
@Override @SuppressWarnings("unchecked") public List<Map<Object, Object>> decode(List<Object> parts, State state) { Map<Object, Object>[] res = parts.toArray(new Map[parts.size()]); return Arrays.asList(res); } ... /** * Extract a filtered set of PropertyDescriptors from the given BeanWrapper, * excluding ignored dependency types or properties defined on ignored dependency interfaces.
🌐
W3Resource
w3resource.com › java-tutorial › arraylist › arraylist_toarray.php
Java arraylist toarray(t a) - w3resource
The toArray() method is used to get an array which contains all the elements in ArrayList object in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array.
Find elsewhere
🌐
Scaler
scaler.com › home › topics › toarray() in java
toArray() in Java - Scaler Topics
May 4, 2023 - This function either takes in no parameter as per the first syntax or takes in an array of Type T in which the element of the list will be stored. The toArray() method returns an Object array if no parameter is passed. Otherwise, if an array is passed as an argument, it returns a new array of Type T i.e.
🌐
Baeldung
baeldung.com › home › java › java array › collection.toarray(new t[0]) or .toarray(new t[size])
Collection.toArray(new T[0]) or .toArray(new T[size]) - Java
January 8, 2024 - Before aimlessly invoking the toArray method, let’s understand what’s inside the box. The Collection interface offers two methods to transform a collection into an array: ... Both methods return an array containing all elements of the collection. To demonstrate this, let’s create a list of natural numbers:
🌐
LeetCode
leetcode.com › discuss › general-discussion › 347421 › question-about-toarray-method-java
Question about toArray() method, Java - Discuss - LeetCode
Question about toArray() method, Java · usta06 · 2590 · Jul 30, 2019 · Any idea why the following gives: error: no suitable method found for toArray(int[]) Thanks! List<Integer> ll = new ArrayList<>(); ll.add(0); int[] tt = new int[ll.size()]; tt = ll.toArray( tt ); System.out.println(tt[0]); 1 ·
🌐
GeeksforGeeks
geeksforgeeks.org › java › arraylist-array-conversion-java-toarray-methods
ArrayList to Array Conversion in Java : toArray() Methods - GeeksforGeeks
July 23, 2025 - Note: toArray() method returns an array of type Object(Object[]). We need to typecast it to Integer before using as Integer objects. If we do not typecast, we get compilation error.
🌐
W3Docs
w3docs.com › java
How can I convert List<Integer> to int[] in Java?
You can use the toArray() method of the List interface to convert a List to an int[] in Java.
🌐
GeeksforGeeks
geeksforgeeks.org › java › convert-list-to-array-in-java
Convert List to Array in Java - GeeksforGeeks
July 11, 2025 - The toArray() method of the Stream interface can be used to convert the elements of the stream into an array. The Stream.toArray(IntFunction<A[]> generator) method returns an array containing the elements of this stream.
🌐
Upgrad
upgrad.com › home › tutorials › software & tech › converting a list to an array in java
Converting a List to an Array in Java - A Comprehensive Guide
3 weeks ago - The toArray() method returns an array containing all the elements of the List in the same order. In this case, the List contains three elements, so the resulting array, fruitsArray, will also have a size of three.
🌐
TutorialsPoint
tutorialspoint.com › java › util › arraylist_toarray_object.htm
Java ArrayList toArray() Method
We're adding couple of Integers to the ArrayList object using add() method calls per element and using toArray() method, we're getting array from the list and printing that array. package com.tutorialspoint; import java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { // create an empty array list ArrayList<Integer> arrayList = new ArrayList<>(); // use add() method to add elements in the arrayList arrayList.add(0); arrayList.add(1); arrayList.add(2); arrayList.add(3); arrayList.add(4); arrayList.add(5); arrayList.add(6); // get the array Object[] array = arrayList.toArray(); // print the array elements for (Object object : array) { System.out.println(object); } } }
🌐
Vultr Docs
docs.vultr.com › java › examples › convert-a-list-to-array-and-vice-versa
Java Program to Convert a List to Array and Vice Versa | Vultr Docs
November 25, 2024 - This snippet initializes a List<Integer> from a fixed set of values. It then uses toArray() to create an Integer[], specifying a new integer array with zero length as the argument.
🌐
Index.dev
index.dev › blog › convert-list-to-array-java
Convert List to Array in Java: 6 Best Ways
This method uses specific stream operations such as mapToInt(), which generates an IntStream that is able to directly form a primitive int[] array. The avoidance of wrapper objects is paramount for performance-critical operations, particularly ...
🌐
iO Flood
ioflood.com › blog › java-list-to-array
Converting a List to Array in Java: A Detailed Walkthrough
February 26, 2024 - In this case, the List nullList is null, so when we try to call the toArray() method on it, Java throws a NullPointerException. To avoid this, you should always check if your List is null before trying to convert it to an Array. An ArrayStoreException can occur if the type of the elements in the List doesn’t match the type of the Array you’re trying to create. Here’s an example: List<Integer> integerList = Arrays.asList(1, 2, 3); String[] array = integerList.toArray(new String[0]); # Output: # Exception in thread 'main' java.lang.ArrayStoreException: java.lang.Integer