An unmodifiable map means that its keys and valuescannotadd,Deleted map, or updated after creating an unmodifiable map instance. The static factory methods in Map: Map.of() and Map.ofEntries() provide a convenient way to create unmodifiable maps in Java 9>.
Map instances created using the Map.of() and Map.ofEntries() methods have the following characteristics. p>
<strong>Map.of(k1, v1, k2, v2) Map.ofEntries(entry(k1, v1), entry(k2, v2),...)</strong>
import java.util.Map; public class UnmodifiableMapTest { public static void main(String[] args) { Map<String, String> empMap = <strong>Map.of</strong>("101", "Raja", "102", "Adithya", "103", "Jai", "104", "Chaitanya"); System.out.println("empMap - " + empMap); empMap.put("105", "Vamsi"); <strong>// throws UnsupportedOperationException</strong> } }
<strong>empMap - {104=Chaitanya, 103=Jai, 102=Adithya, 101=Raja} Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(Unknown Source) at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(Unknown Source) at UnmodifiableMapTest.main(UnmodifiableMapTest.java:7)</strong>
import java.util.Map; import static java.util.Map.entry; public class UnmodifidMapTest { public static void main(String[] args) { Map<String, String> empMap = <strong>Map.ofEntries</strong>(entry("101", "Raja"), entry("102", "Adithya"), entry("103", "Jai"), entry("104", "Chaitanya")); System.out.println("empMap - " + empMap); } }
<strong>empMap - {102=Adithya, 101=Raja, 104=Chaitanya, 103=Jai}</strong>
The above is the detailed content of In Java 9, how do we create an immutable Map?. For more information, please follow other related articles on the PHP Chinese website!