Create the Immutable ArrayList with List.of() Method Example

In this example, we will see how to create the Immutable ArrayList with Java 9 List.of() method example.

Create the Immutable List Example - Java 9 List.of() Method

Let's use List.of() static factory methods to create immutable lists.
package net.javaguides.corejava.java9;

import java.util.List;

/**
 * Java 9 Immutable List Example
 * @author Ramesh Fadatare
 *
 */
public class ImmutableListExample {

    public static void main(String[] args) {

        // Creating Immutable List
        List < String > fruits = List.of("Banana", "Apple", "Mango", "Orange");
        fruits.forEach(e - > System.out.println(e));

        // You can't add Elements Immutable List
        // fruits.add("Strawberry"); // Exception in thread "main" java.lang.UnsupportedOperationException

        // in single list
        List < String > list = List.of("A", "B", "C", "D");
        list.forEach(e - > System.out.println(e));
    }
}
Output:
Banana
Apple
mango
orange
A
B
C
D

References


Java ArrayList Source Code Examples


Comments