logo image

Java9 way of Creating Immutable Lists, Sets, and Maps

1. Lists

You can create a List of elements with following one liner in Java 9

List<String> coloursList = List.of("red", "green", "blue");

List.of gives you a immutable List which means you can't modify it once created. If you try to modify the list by adding or removing an element it throws java.lang.UnsupportedOperationException

List<String> coloursList = List.of("red", "green", "blue");

this results in

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:70)
	at java.base/java.util.ImmutableCollections$AbstractImmutableList.add(ImmutableCollections.java:76)
	at StringSampleProgram.main(StringSampleProgram.java:13)

2. Sets

You can create a Set of elements with following one liner in Java 9

Set<String> coloursSet = Set.of("red", "green", "blue");

3. Maps

There are two ways you can create Immutable Map in Java9 1. Using Map.ofEntries() You can use ofEntries static method and pass java.util.Map.Entry<K, V> objects to it 2. Using Map.of() You can use of static method and pass keys and values one after another.

Following sample program shows you how to use both of them

import java.util.Map;
import static java.util.Map.entry;

public class Java9Maps {
	public static void main(String[] args) {

		Map<String, String> map1 = Map.ofEntries(entry("key1", "val1"), entry("key2", "val2"), entry("key3", "val3"));

		Map<String, String> map2 = Map.of("key1", "val1", "key2", "val2", "key3", "val3");


{key1=val1, key2=val2, key3=val3}
{key1=val1, key2=val2, key3=val3}