Create Immutable Lists In Java 9 By Static Factory Methods

This quick tutorial is going to illustrate how to create immutable Lists in Java 9 by using convenience static factory methods on the List interface, which were added in JDK 9.

1. Prerequisites

Because will get through some Java 9 examples in this tutorial, below are prerequisites:

  • Java 9 installed in our environment
  • Java 9 supported IDE
  • Build Tools such as Gradle or Maven (optional to run the tests)

You can quickly get a simple Java 9 project set up by following Java 9 Example With Maven And JUnit 5 or Set Up Eclipse, IntelliJ And NetBeans For Java 9.

The sample sources presented in this tutorial is available on my Github project. It’s a Maven-based project, so it’s easy to run or imported in any IDE.

2. Syntax

Let’s take a quick look at the syntax of the convenience static factory methods to create immutable Lists in Java 9:

And let’s see an example which we create a list of fruits in Java 9 using the above syntax:

Here is how the list can be created in Java 8:

3. Characteristics of The Immutable List Static Factory Methods

As we can see from above, the List.of() static factory methods provide a convenient way to create immutable lists. And the List instances created by these methods have the following characteristics:

  • They are structurally immutable. Elements cannot be added, removed, or replaced. Calling any mutator method will always cause UnsupportedOperationException to be thrown, for example:
  • However, they can contain elements are themselves mutable, this may cause its contents to appear to change, for example:
  • They disallow null elements. If we attempt to create them with null elements then a NullPointerException will be thrown, for example:
  • The order of elements in the list is the same as the order of the provided arguments, or of the elements in the provided array, for example:
  • They are serializable if all elements are serializable and they are serialized as specified on the Serialized Form page, for example:

4. Conclusions

The tutorial has illustrated about the immutable List static factory methods and how to use those to create immutable Lists in Java 9. We can see that the immutable methods are very convenient for us to initialize a list from known values, and that never changes. And we always should consider using these methods if our data changes infrequently.

Below are related articles for your references:

Java 9 JShell Cheat Sheet

Install Oracle Java 9 on CentOS, RHEL 7

Install Oracle Java 9 on Ubuntu 16.04 LTS (Xenial Xerus)

Private Interface Methods In Java 9

Using The InputStream.transferTo() To Copy Streams In Java 9

Streams API Updates In Java 9

How To Compare Arrays In Java 9

Java 9 – Effectively Final Variables In try-with-resources

Java 9 HTTP/2 Client API Example