Convert List to Array and Vice versa

Learn to convert a list to an array in Java and also convert a given array to a list. We will learn the conversions using the core Java APIs.

  • In Java, Lists are the index based ordered collections that provide random access to the elements by their integer index location.
  • Arrays are also similar to lists but they are stored in a contiguous memory. This is the reason that resizing the arrays is an expensive operation.

1. Converting a List to Array

We can use the following two approaches to convert a given list to an array.

1.1. List.toArray()

Using list.toArray() is the most straightforward way for the list to array conversion. It is an overloaded function.

  • Object[] toArray() : returns an array containing all of the elements in the list.
  • <T> T[] toArray(T[] a) : returns an array containing all of the elements in the list and the type of the returned array is that of the specified array a.
    If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated of the size of given list. If the specified array is bigger than the list then spare indices are filled with null.
  • default <T> T[] toArray(IntFunction<T[]> generator) : returns an array containing all of the elements in the list and the provided generator function is used to allocate the returned array.

Let’s see some examples of these methods.

List<String> list = Arrays.asList("A", "B", "C");

String[] stringArray;

//1
Object[] objArray = list.toArray(); 

//2
stringArray = list.toArray(new String[0]);

//3
stringArray = list.toArray(String[]::new);

1.2. Stream.toArray()

The stream.toArray() method is similar to the list.toArray() method discussed above. It is also an overloaded method.

  • Object[] toArray() : returns an array containing the elements of the stream obtained from the list.
  • <A> A[] toArray(IntFunction<A[]> generator) : returns an array containing the elements of the stream obtained from the list and the generator function used to allocate the returned array.
List<String> list = Arrays.asList("A", "B", "C");

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

The benefits of using the streams are as follows:

  • We can use the list.parallelStream() if the list size is considerably bigger to be processed in a single thread. Parallel streams enable us to execute code in parallel on separate cores. However, the order of execution is out of our control so the items in the array will not be in same order as in the list.
  • Another advantage is that we can apply intermediate stream operations such as filter() if we need to fill only selected items from the list.

For example, in the given code, we do want to fill the array with the list items only starting with character ‘A‘.

String[] filteredArray = list.stream()
        .filter(s -> s.equals("A"))
        .toArray(String[]::new);

2. Converting an Array to List

Converting an array to list in Java is rather a more simple job. We need to use the Arrays.asList() API.

  • Note that the returned list is a fixed-size list backed by the given array. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.
  • Any method invoked on the list, that can change its size, will throw UnsupportedOperationException. Still we can change the items in the list.
String[] stringArray = new String[]{"A", "B", "C"};

List<String> list = Arrays.asList(stringArray);

//changes the list and the array
list.set(0, "Aa");

//Both array and the list are changed
System.out.println(list);	//[Aa, B, C]
System.out.println(Arrays.toString(stringArray));	//[Aa, B, C]

list.add("D"); //java.lang.UnsupportedOperationException

To create an immutable list, we should use Collections.unmodifiableList() API.

String[] stringArray = new String[]{"A", "B", "C"};

List<String> list = Collections.unmodifiableList(Arrays.asList(stringArray));

//Cannot change the list
list.set(0, "Aa"); //java.lang.UnsupportedOperationException

To create a new mutable list, independent of the array, we can use the stream API to iterate over the array and populate the list one item at a time.

String[] stringArray = new String[]{"A", "B", "C"};

List<String> list = Stream.of(stringArray)
	.collect(Collectors.toList());

//changes the list but NOT the array
list.add("D");

//List has been updated but the array is unchanged
System.out.println(list);	//[A, B, C, D]
System.out.println(Arrays.toString(stringArray));	//[A, B, C]

3. Conclusion

In this short tutorial, we learned to convert a list (e.g. ArrayList) to an array using the list.toArray() and stream.toArray() methods. Similarly, we learned to get the list from an array using the Arrays.asList() method.

There are a few other ways, for example using Apache Commons and Guava APIs, but it is overkill to do this simple job without any clear benefit.

Happy Learning !!

Sourcecode on Github

Leave a Reply

0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial