Core Java

Java 8 Convert an Array to List Example

Photo of YatinYatinJanuary 24th, 2018Last Updated: February 25th, 2019
0 4,133 4 minutes read

Hello readers, in this tutorial, we will learn to convert the primitive array to list using the Java8Stream 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 anArray, while developers need to store it in aList or, in List’s more specific subclass such asArrayList. This tutorial analyzes the three most commonly usedArray toList 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 arrayT[] to aList<T> using theArrays.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 theintegerList have been copied from theintegerArray.

Code Output

[1, 66, 88, 100, 201]

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

Developers can use the constructor of anArrayList which accepts a collection as an input parameter and initializes a newjava.util.ArrayList instance containing the collection’s data. AnArrayList created in this manner does not have the twin disadvantages we saw in option1.1 viz. Being of fixed size and being just another view into the original array rather than being anArrayList 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 ArrayintegerArray[0]=22;System.out.println(integerList); // Adding a new number to integerListintegerList.add(250);System.out.println(integerList);

As developers can infer from the above code and its output, theintegerList created like this allows adding a new number i.e.250 to theArrayList. Here, the original array’s modification (i.e. by setting theintegerArray[0]=22) does not affect the newly createdintegerList 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 theint array to a list ofInteger.

  • Convert the specified primitive array to a sequential stream using theArrays.stream() method
  • Box each element of the stream to anInteger using theIntStream.boxed() method
  • Use theCollectors.toList() method to accumulate the input elements into a newList

Now, open up the Eclipse Ide and I will explain further about converting anArray of data into an equivalentList.

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 toFile -> 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 apom.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 thesrc/main/java folder,New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation
Want to be a Java 8 Ninja ?
Subscribe to our newsletter and download the Java 8 FeaturesUltimateGuideright now!
In order to get you up to speed with the major Java 8 release, we have compiled a kick-ass guide with all the new features and goodies! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

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 theArrays toList 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 astream() 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 aCollector instance which accepts theStream as input and ‘collects’ its elements into aList 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 ofArray toList conversion in Java8.

Download
You can download the full source code of this example here:Java8Array2List
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of YatinYatinJanuary 24th, 2018Last Updated: February 25th, 2019
0 4,133 4 minutes read
Photo of Yatin

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

Related Articles

Bipartite Graph

Java not equal Example

January 17th, 2020
Bipartite Graph

Java API Tutorial

October 26th, 2020
Bipartite Graph

Java Struct Example

January 8th, 2020
Bipartite Graph

Java Node Example

November 20th, 2019
Bipartite Graph

Java Swing MVC Example

January 26th, 2016
Bipartite Graph

How to call a method in Java

December 26th, 2019
Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.