Java 9: Immutable List, Set and Map

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.

ImmutableJava8

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.

ImmutableList.JPG

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.

ImmutableSet.JPG

ImmutableMap.JPG

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s