Factory method to create Immutable Collection in Java 9 |
Posted: April 4, 2023 |
In Java 9 we can use “of()” factory methods to create immutable List, Set and Map. Until Java 8 we have to write a lot of lines of code to create immutable Lists, Sets and Maps. But from Java 9 onwards we can create an immutable List, Set and Map with a single line of code with factory methods. Table of content
1. How to create Immutable List?We can create immutable Lists by using List.of() factory methods in Java 9. There are 12 overloaded “of()” factory methods of List in Java 9: Example:We cannot add, remove, or replace elements in the immutable List. Calling any mutator method of List will always cause UnsupportedOperationException to be thrown in the immutable List. 2.How to create Immutable Set?We can create immutable Sets by using Set.of() factory methods in Java 9. There 12 several overloaded “of()” factory methods of Set in Java 9: Example:Output: 3. How to create ImmutableMap?We can create immutable Maps by using Map.of() factory methods in Java 9. There 11 several overloaded “of()” factory methods of Map in Java 9: Example:Output: 4. ConclusionIn this topic, we learnt about How to create Immutable List in Java 9? How to create Immutable Set in Java 9? How to create Immutable Map in Java 9?
|
|||||||||||||||||||||||||||||||||||||||||||
|