How To Convert List To Array in Java

Table of Contents

A common scenario faced by programmers is to convert a Java List to an Array. A ‘List’ is part of the Collection Framework and is useful when the number of elements are unknown. An ‘Array’, on the other hand, is useful for fixed-size elements.

However, in real-world programming, there are often situations when you would need to convert a List to an array like for example while dealing with methods that expect an array as input. There are several ways that you can achieve this. In the next few sections, I will be going over each method in detail.

1. Using a ‘For Loop’

The simplest way to convert a List to an array is to use a for loop.  The following code demonstrates this:

public static void convertUsingForLoop(){
List<Integer> inputList = Arrays.asList(2,4,6,8,10);
int[] outputArray = new int[inputList.size()];
for(int i = 0; i < inputList.size();i++){
      outputArray[i] = inputList.get(i);
   }
   //print the elements in the array
   for (int num : outputArray) {
      System.out.print(num + " ");
   }
}

First, the code creates an array based on the number of elements in the input List. A for-loop is then used which iterates through the input List and adds each element of the List to an array. Finally, another for loop is used to print each element in the array. So this code prints the following output:

2 4 6 8 10

2. Using ‘toArray’

Java provides a toArray method on the List interface. This can be used to convert a List to an array. There are two overloaded versions of this method as explained below.

(2.1) List.toArray without parameters

This toArray method does not accept any input parameters. It returns an object array. The following code demonstrates this approach:

public static void convertUsingToArray() {
List<Integer> inputList = Arrays.asList(2, 4, 6, 8, 10);
   Object[] objArray = inputList.toArray();

//print the elements in the array
   for (Object num : objArray) {
      System.out.print(num + " ");
   }
}

Here, the toArray method is invoked on the input List which returns an object array. So this code prints the same output as before:
2 4 6 8 10

(2.2) List.toArray with parameters

There is an overloaded version of the toArray method. This accepts an array as a parameter and returns a result array which is of the same data type as the input array.

So basically, this toArray method can be used to obtain an array which is of the same data type as the input List instead of an object array. The following code demonstrates this approach:

public static void convertUsingToArray2() {

List<Integer> inputList = Arrays.asList(2, 4, 6, 8, 10);
   Integer[] outputArray = inputList.toArray(new Integer[inputList.size()]);
   
//print the elements in the array
   for (int num : outputArray) {
      System.out.print(num + " ");
   }
}

So in this case, the toArray method is invoked with an Integer array which is of the same size as the input List. It then returns an Integer array. So this code prints the same output as before:
2 4 6 8 10

3. Using Stream API

Java 8 has added the Stream API that helps to easily perform bulk operations on Collections. A new method called stream() has been added to all the collection interfaces that returns a Stream corresponding to the underlying collection.

There is a toArray method available on the Stream interface that can be used to convert the Stream to an array. So this method can be used to convert a List to an array. There are two overloaded versions of this method as explained below.

(3.1) stream.toArray without parameters

This Stream.toArray method does not accept any input parameter and it returns an object array. The following code demonstrates this approach:

This Stream.toArray method does not accept any input parameter and it returns an object array. The following code demonstrates this approach:
public static void convertUsingStream() {
List<Integer> inputList = Arrays.asList(2, 4, 6, 8, 10);
   Stream<Integer> inputStream = inputList.stream();
   Object[] objArray = inputStream.toArray();

//print the elements in the array
   for (Object num : objArray) {
      System.out.print(num + " ");
   }
}

Here, first the stream() method is invoked on the input List. This returns a Stream corresponding to the List. Then the toArray method is invoked on the Stream. This returns an object array. So this code prints the same output as before:
2 4 6 8 10

(3.2) stream.toArray with parameters

There is an overloaded version of the Stream.toArray method which can be used to return a result array which is of the same data type as the input array. The following code demonstrates this:

public static void convertUsingStream2() {
List<Integer> inputList = Arrays.asList(2, 4, 6, 8, 10);
Stream<Integer> inputStream = inputList.stream();
   Integer[] intArray = inputStream.toArray((num) -> new Integer[num]);
   
//print the elements in the array
   for (int num : intArray) {
      System.out.print(num + " ");
   }
}

As before, first the stream() method is invoked on the input List which returns a Stream corresponding to the List. Then the overloaded toArray method is invoked. This method accepts an IntFunction interface as a parameter which is an in-built functional interface that accepts an input of integer data type and returns a result of any data type.

Here, it is implemented via a lambda expression that accepts as input the length of the array and returns an Integer array of the specified length. So this is then used by the Stream.toArray method to create the output array. So this code prints the same output as before:
2 4 6 8 10

Conclusion

So this article demonstrates the different ways in which a List can be converted to an array in Java.

Tushar Sharma
Tushar Sharmahttps://www.automationdojos.com
Hi! This is Tushar, the author of 'Automation Dojos'. A passionate IT professional with a big appetite for learning, I enjoy technical content creation and curation. Hope you are having a good time! Don't forget to subscribe and stay in touch. Wishing you happy learning!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

RELATED POSTS

How To Concatenate Strings in Java

Introduction In Java, a String is a sequence of characters. There are often programming situations where you will need to concatenate Strings. There are several...

Java Tutorial #7 Part 1 – Classes & Objects

Classes are a very important concept in Java. Java code always needs to be written in a class. In this article, we will be...

Getting Started With Hibernate

Introduction Hibernate is a framework which allows you to access database tables from Java code. Before Hibernate came into existence, JDBC was widely used. JDBC...

Â

RECENT 'HOW-TO'

How To Install Oh-My-Posh On Windows PowerShell

Oh-My-Posh is a powerful custom prompt engine for any shell that has the ability to adjust the prompt string with a function or variable. It does not...

SIMILAR ON CODEX

FEATURED PROJECTS

Windows JDK Manager (win-jdk-Manager)

ADjo LABS PROJECT : Simple and lightweight desktop utility with Interactive cmd Interface for easy view, re-point and switching between JAVA versions on windows. Demonstrating the capability...

MORE IN THIS CATEGORY

How To Do Database Testing with JMeter

Introduction In this 'How-To', You will be guided to perform a database load test using JMeter. We will be installing Apache JMeter to perform the...

How To Install Pacman For Git on Windows

The 'Git for Windows' by default does not come with MSYS2 package manager called 'Pacman' and hence it is a limited version or subset...

Remove Duplicates from List Using LinkedHashSet

Another implementation of the Set interface is LinkedHashSet. LinkedHashSet maintains the order of elements and helps to overcome the HashSet limitation. The following code...

CHECKOUT TUTORIALS

VBS Part 2 – Fundamentals and Concepts

Having gone through the Introductory part, it is time to look at some crucial fundamentals and concepts. This article is to refresh some of...
- Advertisement -spot_img