Java 9 provides a convenient way to create an immutable collections such as List, Set and Map. In this post, we are going to see that with few examples.
Prior to Java 9, To create an immutable collections, we have to follow the below approach. It works fine but its verbose.
Now, in Java 9, we can easily, create an immutable list with the List.of() method.
The List.of method returns an instance of “java.util.ImmutableCollections.ListN” [extends AbstractImmutableList]. As this class extends AbstractImmutableList, the returned list is an immutable list, so trying to update it, will throw UnsupportedOperationException.
We can follow the same way for creating an immutable Set and Map. Refer the below examples.
The Set.of method returns an instance of “java.util.ImmutableCollections.SetN” [extends AbstractImmutableSet]. Its immutable so trying to update it, will throw UnsupportedOperationException.
The Map.of method returns an instance of “java.util.ImmutableCollections.MapN” [extends AbstractImmutableMap]. Its immutable so trying to update it, will throw UnsupportedOperationException.