Single Line List Initialization

JavaJavaBeginner
Practice Now

Introduction

In Java, we can initialize a List in a single line of code using a variety of approaches. In this lab, we will learn different methods to initialize Lists in Java in a concise way.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/generics("`Generics`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/arraylist("`ArrayList`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/comments("`Comments`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117970{{"`Single Line List Initialization`"}} java/generics -.-> lab-117970{{"`Single Line List Initialization`"}} java/arraylist -.-> lab-117970{{"`Single Line List Initialization`"}} java/classes_objects -.-> lab-117970{{"`Single Line List Initialization`"}} java/class_methods -.-> lab-117970{{"`Single Line List Initialization`"}} java/modifiers -.-> lab-117970{{"`Single Line List Initialization`"}} java/oop -.-> lab-117970{{"`Single Line List Initialization`"}} java/packages_api -.-> lab-117970{{"`Single Line List Initialization`"}} java/identifier -.-> lab-117970{{"`Single Line List Initialization`"}} java/arrays -.-> lab-117970{{"`Single Line List Initialization`"}} java/comments -.-> lab-117970{{"`Single Line List Initialization`"}} java/data_types -.-> lab-117970{{"`Single Line List Initialization`"}} java/operators -.-> lab-117970{{"`Single Line List Initialization`"}} java/output -.-> lab-117970{{"`Single Line List Initialization`"}} java/strings -.-> lab-117970{{"`Single Line List Initialization`"}} java/system_methods -.-> lab-117970{{"`Single Line List Initialization`"}} end

Using Arrays.asList() Method

We can create a List using an array by using the asList() method. This method directly takes the elements as parameters and returns a fixed-size list. If an attempt is made to add an element, an UnsupportedOperationException is thrown.

import java.util.Arrays;
import java.util.List;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = Arrays.asList("red", "blue", "green");
        System.out.print("Colors List : " + colorsList); //Output : [red, blue, green]
    }
}

To run the code opencommand prompt, navigate to the project directory and run the following commands:

javac ListInitializationDemo.java
java ListInitializationDemo

Using Java 8 Streams

Java Streams can be used to create a List for the stream elements using collect() method.

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = Stream.of("red", "blue", "green")
                                        .collect(Collectors.toList());
        System.out.print("Colors List : " + colorsList); //Output : [red, blue, green]
    }
}

To run the code open command prompt, navigate to the project directory and run the following commands:

javac ListInitializationDemo.java
java ListInitializationDemo

Using List.of() Method

Java 9 provides an overloaded List.of() method for both mutable and immutable Lists.

import java.util.List;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = List.of("red", "blue", "green");
        System.out.print("Colors List : " + colorsList); //Output : [red, blue, green]
    }
}

To run the code open command prompt, navigate to the project directory and run the following commands:

javac ListInitializationDemo.java
java ListInitializationDemo

Using Double Brace Syntax

Double Brace Initialization can be used to an Anonymous Inner Class to initialize a List.

import java.util.List;
import java.util.ArrayList;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = new ArrayList<String>() {
            {
                add("red");
                add("blue");
                add("green");
            }
        };
        System.out.print("Colors List : " + colorsList); //Output : [red,blue,green]
    }
}

To run the code open command prompt, navigate to the project directory and run the following commands:

javac ListInitializationDemo.java
java ListInitializationDemo

Using Apache Commons Collections

Apache Commons Collections provides the unmodifiableList() method that returns an unmodifiable view of the specified list.

import java.util.List;
import org.apache.commons.collections4.ListUtils;
import java.util.Arrays;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = ListUtils.unmodifiableList(
                Arrays.asList("red", "blue", "green")
        );
        System.out.print("Colors List : " + colorsList); //Output : [red,blue,green]
    }
}

To run the code, open the terminal, go to the project directory and run the following commands:

javac -cp commons-collections4-4.4.jar ListInitializationDemo.java
java -cp commons-collections4-4.4.jar:. ListInitializationDemo

Using Guava Library

The Guava library provides the newArrayList() method that returns a mutable ArrayList initialized with the elements.

import java.util.List;
import com.google.common.collect.Lists;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = Lists.newArrayList("red", "blue", "green");
        System.out.print("Colors List : " + colorsList); //Output : [red,blue,green]
    }
}

To run the code, open the terminal, go to the project directory and run the following commands:

javac -cp guava-31.0.1-jre.jar ListInitializationDemo.java
java -cp guava-31.0.1-jre.jar:. ListInitializationDemo

Using Guava's ImmutableList

Guava also provides the ImmutableList class that returns an immutable List.

import java.util.List;
import com.google.common.collect.ImmutableList;

public class ListInitializationDemo {
    public static void main(String[] args) {
        List<String> colorsList = ImmutableList.of("red", "blue", "green");
        System.out.print("Colors List : " + colorsList); //Output : [red,blue,green]
    }
}

To run the code, open the terminal, go to the project directory and run the following commands:

javac -cp guava-31.0.1-jre.jar ListInitializationDemo.java
java -cp guava-31.0.1-jre.jar:. ListInitializationDemo

Summary

In Java, there are numerous ways to initialize a List in a single line of code. We have seen ways to use Java 8 Stream for creating a List, use of Arrays.asList() method, and the List.of() method for Java versions after 9. We have also seen Double Brace Initialization and an example of how external Java libraries like Apache Commons Collections and Guava can be used.

Other Java Tutorials you may like