Factory method to create immutable Map in Java 9
Last Updated :
11 Dec, 2018
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:
import java.util.*;
class ImmutableListDemo
{
public static void main(String args[])
{
Map<Integer, String> empty = new HashMap();
Map immutable1 = Collections.unmodifiableMap(empty);
Map<Integer, String> non_empty = new HashMap();
non_empty.put( 1 , "ide" );
Map immutable2 = Collections.unmodifiableMap(non_empty);
immutable1.put( 1 , "gfg" );
immutable2.put( 2 , "quiz" );
}
}
|
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:
import java.util.*;
class ImmutableListDemo
{
public static void main(String args[])
{
Map<Integer, String> immutable1 = Map.of();
Map<Integer, String> immutable2 = Map.of( 1 , "ide" , 2 , "quiz" );
immutable1.put( 1 , "gfg" );
immutable2.put( 3 , "contribute" );
}
}
|
After running above code, we will have UnsupportedOperationException.
Java code to create immutable map using Map.ofEntries() method in Java 9:
import java.util.*;
import java.util.Map.Entry;
class ImmutableListDemo
{
public static void main(String args[])
{
Map<Integer, String> immutable = Map.ofEntries();
Map.Entry<Integer, String> entry1 = Map.entry( 1 , "gfg" );
Map.Entry<Integer, String> entry2 = Map.entry( 2 , "contribute" );
Map<Integer, String> immubatleMap = Map.ofEntries(entry1,
entry2);
}
}
|
So of() and ofEntries() are method used to create immutable map in java 9.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...