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

Format Decimal Numbers with Grouping Separator

The DecimalFormat class has a method called setGroupingSize() which sets how many digits of the integer part to group. Groups are separated by the...

Java DecimalFormat Class

When you need to format decimal numbers, such as taking three or two decimal places for a number, showing only the integer part of...

Concatenate Strings Using StringBuilder.append()

In addition to String, Java has the java.lang.StringBuffer and java.lang.StringBuilder classes. These can also be used to concatenate Strings. The advantage of these...

Â

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

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...

How To Record Using BlazeMeter Plugin (JMeter)

Honestly speaking if you already have a mature or established process using 'native' JMeter from Apache, without any kind of wrappers utilities or third-party...

Create Basic Hibernate Program

Hibernate is an ORM framework that helps in accessing database tables from Java code. It is an object-oriented way of accessing database tables and...

CHECKOUT TUTORIALS

VBS Part 1 – Introduction and Background

At the upfront, this theoretical article might look boring to most of us but still, it is advisable to know about our scripting friend...
- Advertisement -spot_img