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

Convert String to java.time.LocalDate without Formatter

The LocalDate class has a parse method. You can use this to convert a String to a LocalDate. So, this code simply invokes the...

Remove Duplicates from List Using For-Loop

The simplest way to remove duplicates from a 'List' is to use a for-loop. The following code snippet demonstrates this method. First, the code creates...

Convert List to Array Using ToArray With Param

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

Â

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

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

Format Decimal Numbers Using Format Symbols

You can customize which symbols are used as decimal separator, grouping separator, currency seperator etc. using a DecimalFormatSymbols instance together with java.text.DecimalFormat class. The...

Does VBScript Supports all COM Objects ?

Well the answer in one line is - No VBScript does not supports all COM Objects or Servers! VBScript works with only a subset of ‘Objects’...

CHECKOUT TUTORIALS

Java Tutorial #5 – Loop Statements

Iteration statements are used to repeat a particular block of code until a certain condition is true. In this article, we will be taking...
- Advertisement -spot_img