Factory method to create Immutable Map in Java SE 9


With Java 9, new factory methods are added to Map interface to create immutable instances. These factory methods are convenience factory methods to create a collection in less verbose and in concise way.

Old way to create collections

Example

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Tester {
   public static void main(String []args) {

      Map<String, String> map = new HashMap<>();

      map.put("A","Apple");
      map.put("B","Boy");
      map.put("C","Cat");
      Map<String, String> readOnlyMap = Collections.unmodifiableMap(map);
      System.out.println(readOnlyMap);
      try {
         readOnlyMap.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following output.

{A = Apple, B = Boy, C = Cat}
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.remove(Collections.java:1460)
at Tester.main(Tester.java:15)

New Methods

With java 9, following methods are added to Map interface along with their overloaded counterparts.

static <E> Map<E> of(); // returns immutable set of zero element
static <E> Map<E> of(K k, V v); // returns immutable set of one element
static <E> Map<E> of(K k1, V v1, K k2, V v2); // returns immutable set of two elements
static <E> Map<E> of(K k1, V v1, K k2, V v2, K k3, V v3);
//...
static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)// Returns an immutable map containing keys and values extracted from the given entries.

Points to Note

  • For Map interface, of(...) method is overloaded to have 0 to 10 parameters and ofEntries with var args parameter.

  • These methods returns immutable map and elements cannot be added, removed, or replaced. Calling any mutator method will always cause UnsupportedOperationException to be thrown.

New way to create immutable collections

Example

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class Tester {
   public static void main(String []args) {

      Map<String, String> map = Map.of("A","Apple","B","Boy","C","Cat");
      System.out.println(map);
      try {
         map.remove(0);
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Output

It will print the following output.

{A = Apple, B = Boy, C = Cat}
java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.remove(Collections.java:1460)
at Tester.main(Tester.java:15)

Vikyath Ram
Vikyath Ram

A born rival

Updated on: 21-Jun-2020

117 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements