Initialize Immutable Collections in Java

Immutable Collection likes an Immutable Object, once created, we can not edit anything on that Object or Collection. From Java 8 and earlier, to initialize an Immutable Collection like List, Set, or Map, we will use the unmodifiableXXX() methods in the java.util.Collections class.

For example, we create an immutable object of List as follows:

If now, you want to add new value to the students object:

below error will happen:

Initialize Immutable Collections in Java

From Java 9, Java adds new static method of() to List, Set, Map object, which makes it easier to initialize the Immutable Collection.

For example, now to initialize an Immutable List, we just need to write code like this:

With an Immutable Set, it is still same like with Immutable List:

With Immutable Map, there is a little different. For example, from Java 8 and earlier, we will write:

But for Java 9, we can write down the following:

As you can see with the Immutable Map, we will pass to the static method of(), key and value of the Map in order (key1, value1, key2, value2, …).

Result:

Initialize Immutable Collections in Java


Add Comment