How to create a list using List.of() method?

By IncludeHelp Last updated : February 4, 2024

Java9 added a method List.of() in the java.util.List class that can be used to create a list.

What is List.of() Method in Java?

The List.of() method is used to construct a compact and unmodifiable list. It a method of List class in java.util package. The List.of() method can take in any number of arguments to construct a list.

Syntax

Below is the syntax of the List.of() method:

List<Type_Wrapper_Class> list = List.of(elements);

Creating a list using List.of() method

To create a list using the List.of() method, specify the type class (Integer, String, etc.), and use the List.of() method by passing the elements of the list.

Syntax

Below is the syntax to create an Integer list:

List listInts= List.of(10, 20, 30);

Syntax

Below is the syntax to create a String list:

List citiesList = List.of("New Delhi", "Mumbai", "Indore");

Java example to create a list using List.of() method

This example creates a list of integers using List.of() method.

// Importing the required classes
import java.util.List;

// The Main Class
public class Main {
  public static void main(String args[]) {

    // Creating a list of integers 
    // using List.of() method
    List < Integer > list = List.of(10, 20, 30, 40, 50);

    // Printing the List 
    System.out.println("List of integers : " + list.toString());
  }
}

Output

The output of the above example is:

List of integers : [10, 20, 30, 40, 50]

To understand this program, you should have the basic knowledge of the following Java topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.