Core Java

Java 8 Convert an Array to List Example

Hello readers, in this tutorial, we will learn to convert the primitive array to list using the Java8 Stream API.

1. Introduction

Converting an Array of data into an equivalent List does seem like one of the simplest tasks which a programmer would do when coding in Java. There are many scenarios where the data is present in an Array, while developers need to store it in a List or, in List’s more specific subclass such as ArrayList. This tutorial analyzes the three most commonly used Array to List conversion options.

1.1 Using Arrays.asList() method to convert from an Array to a List

This is one of the most common ways of converting an array T[] to a List<T> using the Arrays.asList() method. It can be coded for in a single line of code as shown below.

Option1.java

Integer integerArray[] = {1,66,88,100, 201};
List<Integer> integerList= Arrays.asList(integerArray);
System.out.println(integerList);

As we can see in the below output, members of the integerList have been copied from the integerArray.

Code Output

[1, 66, 88, 100, 201]

1.2 Using ArrayList constructor with Arrays.asList() as parameter

Developers can use the constructor of an ArrayList which accepts a collection as an input parameter and initializes a new java.util.ArrayList instance containing the collection’s data. An ArrayList created in this manner does not have the twin disadvantages we saw in option 1.1 viz. Being of fixed size and being just another view into the original array rather than being an ArrayList instance on its own. Let us now see a code snippet showing this option in use.

Option2.java

Integer integerArray[] = {1,66,88,100, 201};
List<Integer> integerList= new ArrayList<>(Arrays.asList(integerArray));
System.out.println(integerList);
 
// Modifying the Original Array
integerArray[0]=22;
System.out.println(integerList);
 
// Adding a new number to integerList
integerList.add(250);
System.out.println(integerList);

As developers can infer from the above code and its output, the integerList created like this allows adding a new number i.e. 250 to the ArrayList. Here, the original array’s modification (i.e. by setting the integerArray[0]=22) does not affect the newly created integerList which is now an independent instance in itself.

Code Output

[1, 66, 88, 100, 201]
[1, 66, 88, 100, 201]
[1, 66, 88, 100, 201, 250]

1.3 Using Java 8’s Arrays.stream() method with a Collector

Java8’s Arrays class provides a method i.e. stream() which has overloaded versions of accepting both Primitive arrays and Object arrays. Below are the steps developers can use to convert the int array to a list of Integer.

  • Convert the specified primitive array to a sequential stream using the Arrays.stream() method
  • Box each element of the stream to an Integer using the IntStream.boxed() method
  • Use the Collectors.toList() method to accumulate the input elements into a new List

Now, open up the Eclipse Ide and I will explain further about converting an Array of data into an equivalent List.

2. Java8 Convert an Array to List Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Java8Array2List</groupId>
	<artifactId>Java8Array2List</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java.

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to demonstrate the Arrays to List conversion. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: Java8Array2List. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (Java8Array2List.java)
Fig. 8: Java Class (Java8Array2List.java)

3.1.1 Example on Array to List Conversion

Java 8’s Arrays class provides a stream() method which has overloaded versions accepting both primitive arrays and Object arrays. Here is the complete Java program to demonstrate this in the Java8 programming.

Java8Array2List.java

package com.jcg.java;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**** Program to Convert 'int' Array to 'List' of Integer ****/
public class Array2ListDemo {

	public static void main(String[] args) {

		/**** Converting a Primitive 'int' Array to List ****/
		int intArray[] = {1, 2, 3, 4, 5};
		List<Integer> integerList1 = Arrays.stream(intArray).boxed().collect(Collectors.toList());
		System.out.println("List #1: " + integerList1);

		/**** 'IntStream.of' or 'Arrays.stream' Gives The Same Output ****/
		List<Integer> integerList2 = IntStream.of(intArray).boxed().collect(Collectors.toList());
		System.out.println("List #2: " + integerList2);

		/**** Converting an 'Integer' Array to List ****/
		Integer integerArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		List<Integer> integerList3 = Arrays.stream(integerArray).collect(Collectors.toList());
		System.out.println("List #3: " + integerList3);
	}
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

In the above code, arrays of both Primitive and Object types are converted to streams of their respective types first. The individual Streams are then fed, or pipelined to a Collector instance which accepts the Stream as input and ‘collects’ its elements into a List which is of the same type as the type of the original array. The code shows the following logs as output.

# Logs for 'Array2ListDemo' #
=============================
List #1: [1, 2, 3, 4, 5]
List #2: [1, 2, 3, 4, 5]
List #3: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at the 3 popularly used ways of converting a given Array into an equivalent List. I hope this article served you whatever you were looking for.

7. Download the Eclipse Project

This was an example of Array to List conversion in Java8.

Download
You can download the full source code of this example here: Java8Array2List

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button