How can we create an unmodifiable Map in Java 9?

JavaObject Oriented ProgrammingProgramming

An unmodifiable Map is one whose keys and values can't be added, removed, or updated once an unmodifiable instance of a map has created. The static factory methods: Map.of() and Map.ofEntries() from Map that provides a convenient way to create unmodifiable maps in Java 9.

An instance of a map created by using Map.of() and Map.ofEntries() methods has the following characteristics.

  • The map returned by the factory methods is conventionally immutable. It means that keys and values can't be added, removed, or updated. Calling any mutator method on the map causes an UnsupportedOperationException.
  • If the contained keys/values of a map are themselves mutable, it may cause Map to behave in-consistently or its contents to appear to change.
  • An immutable map doesn't allow null keys and values. If any attempt to create with null keys or values, then it throws NullPointerException.
  • The duplicate keys are rejected at the time of creation itself. Passing duplicate keys to a static factory method causes IllegalArgumentException.
  • The immutable maps are serializable if all keys and values are serializable.
  • The order of iteration of mappings is unspecified and subject to change.

Syntax

Map.of(k1, v1, k2, v2)
Map.ofEntries(entry(k1, v1), entry(k2, v2),...)

Example of Map.of()

import java.util.Map;
public class UnmodifiableMapTest {
   public static void main(String[] args) {
      Map<String, String> empMap = Map.of("101", "Raja", "102", "Adithya", "103", "Jai", "104", "Chaitanya");
      System.out.println("empMap - " + empMap);
      empMap.put("105", "Vamsi");      // throws UnsupportedOperationException
   }
}

Output

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)


Example of Map.ofEntries()

import java.util.Map;
import static java.util.Map.entry;
public class UnmodifidMapTest {
   public static void main(String[] args) {
      Map<String, String> empMap = Map.ofEntries(entry("101", "Raja"), entry("102", "Adithya"), entry("103", "Jai"), entry("104", "Chaitanya"));
      System.out.println("empMap - " + empMap);
   }
}

Output

empMap - {102=Adithya, 101=Raja, 104=Chaitanya, 103=Jai}
raja
Published on 19-Feb-2020 13:44:06
Advertisements