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

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

How To Create Maven Project in Eclipse With Archetype

Maven Basics Maven automates the steps involved in building a software application like adding the JAR files, compiling code, running unit tests, creating the output...

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to...

Â

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

SEPA Bulk File Generator and Validator

ADjo LABS PROJECT: SEPA Bulk File Generator and Validator. Supported File Types PAIN008, PAIN001, PACS003 and PACS008. Tested for supporting PAIN.008.001.001 and PAIN.008.001.002 (version 1&2). The XML...

MORE IN THIS CATEGORY

Convert String to Date Using SimpleDateFormat Class

Sometimes, you may need to convert a String to a java.util.Date object. For this, you need to use the SimpleDateFormat class. You need to...

How To Find Broken Links with Selenium

What is a broken link? Links are used for navigating between webpages. Users are directed to a web page when they click or type a...

Java Tutorial #4 – Control Statements

Introduction Control statements are used to change the flow of execution based on changes to certain variables in the code. One of the types of...

CHECKOUT TUTORIALS

Getting Started with Selenium WebDriver

Table of Contents 1. Selenium and Selenium Web Driver 2. Setting-Up the Environment 3. Test Script with Selenium Web Driver 3.1) Creating a project 3.2) Creating...
- Advertisement -spot_img