Factory method to create immutable Map in Java 9
In Java 9 there are some features are added in Java language and factory method for immutable map is one of them.
Characteristics of immutable map:
- As the name suggest these map are immutable.
- If any attempt made to add, delete and update elements in the map we will have UnsupportedOperationException.
- Immutable map do not allow null element either.
- If any attempt made to create a immutable map with null element, we will have NullPointerException. If any attempt made to add null element in map, we will have UnsupportedOperationException.
Creating immutable map in Java 8
To create immutable map in java 8, we use java.util.unmodifiableMap(Map map) method. unmodifiableMap(Map map): This method returns an unmodifiable view of the specified map. This method allows modules to provide users with “read-only” access to internal maps.
Syntax: public static Map unmodifiableMap(Map map) Returns: an unmodifiable view of the specified map. Exception: NA
Java code for immutable empty and no-empty map:
Above code will generate exception, because we are trying to add key-value pair in immutable Map.
Runtime Error : Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1457) at ImmutableListDemo.main(File.java:17)
Creating immutable Map in java 9
To create immutable map in java 9, we use of() and ofEntries() method.
Java code to create immutable map in java 9:
After running above code, we will have UnsupportedOperationException.
Java code to create immutable map using Map.ofEntries() method in Java 9:
So of() and ofEntries() are method used to create immutable map in java 9.
This article is contributed by Abhishek Verma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.