Let’s say you want to create a list of objects which cannot be modified.
There are three ways to do this in Java:
- Using Collection Factories
- Using methods in Collections utility class
- Using methods in Collectors utility class
Using Collection Factories:
Java 9 came up with collection factories to create immutable collections.
To create an immutable list use List.of() method and pass in the objects as parameters separated by commas:
As you see adding a new string to the existing list throws an unsupported operation exception.
This was introduced in Java 9 and works for simple scenarios like above.
Using methods in Collections utility class:
In this case , to create an immutable list , create a mutable list and pass it as an argument to Collections.unmodifiableList(input) method:
The same exception is thrown when trying to add a new element to the immutable collection created using unmodifiableList() method.
Collections.unmodifiableSet() can be used to create immutable sets
Collections.unmodifiableMap() can be used to create immutable maps
This was introduced in Java 9 as well
Using methods in Collectors utility class
Java 10 gave one more way of creating immutable collections.
You can stream a mutable list and create a new immutable one using Collectors.toUnmodifiableList() method:
For the mutable list created in the previous example , an immutable list can be created as follows:
As you see, the list is streamed and then collected as a new immutable list.
And adding a new element throws exception.
This method of creating immutable collections is handy since you can do operations like filtering on a collection and then create a new immutable collection out of it easily.
For example to create an immutable list of names only of length 5 , we can do this:
Immutable sets can be created using Collectors.toUnmodifableSet() and
Immutable maps can be created using Collectors.toUnmodifiableMap() methods.