Saturday, July 16, 2022

Unmodifiable or Immutable Map in Java

An unmodifiable Map in Java is one whose keys and values cannot be added, removed, or updated once the unmodifiable instance of a Map is created. In this post we’ll see how Unmodifiable Map was created before Java 9 and how it can be created Java 9 onward using Immutable Map Static Factory Methods.


Creating Unmodifiable Map before Java 9

Till Java 8 in order to create unmodifiable Map Collections.unmodifiableMap() method was used.

Collections.unmodifiableMap(Map<? extends K,? extends V> m)- Returns an unmodifiable view of the specified map. Attempt to modify the returned map, whether direct or via its collection views, result in an UnsupportedOperationException.

Drawback of this method is that the underlying Map is still modifiable let’s try to see it with an example.

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = new HashMap<String, String>();
    alphaMap.put("1", "a");
    alphaMap.put("2", "b");
    alphaMap.put("3", "c");
    alphaMap.put("4", "d");
    Map<String, String> aMap = Collections.unmodifiableMap(alphaMap);
    // still mutable
    alphaMap.put("5", "e");
    System.out.println("alphaMap- " + alphaMap);
    //error as this Map is an unmodifiable view
    aMap.put("6", "f");
  }
}

Output

alphaMap- {1=a, 2=b, 3=c, 4=d, 5=e}
Exception in thread "main" 
java.lang.UnsupportedOperationException
 at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1455)
 at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:20)

As you can see original map alphaMap can still be modified, though the unmodifiable Map view can’t be modified.

Creating Unmodifiable Map in Java 9

The Map.of (Java 9), Map.ofEntries (Java 9), and Map.copyOf (Java 10) static factory methods provide a convenient way to create unmodifiable maps. The Map instances created by these methods have the following characteristics:

  1. They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method results in UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  2. Immutable maps don't allow null keys and values. Attempts to create them with null keys or values result in NullPointerException.
  3. Duplicate keys are rejected at creation time itslef. Passing duplicate keys to a static factory method result in IllegalArgumentException.
  4. Immutable maps are serializable if all keys and values are serializable.
  5. The iteration order of mappings is unspecified and is subject to change.

Java Map.of() methods for creating unmodifiable Map

Map.of() static factory method is a convenient way to create unmodifiable maps Java 9 onward. This method is overloaded to have up to 10 elements and the form of the method is as follows.

Map.of()- Returns an unmodifiable map containing zero mappings. 
Map.of(K k1, V v1)- Returns an unmodifiable map containing a single mapping.
..
..
Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9)- Returns an unmodifiable map containing nine mappings. 
Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)- Returns an unmodifiable map containing ten mappings.

Map.of() method Java example

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = Map.of("1","a", "2","b", "3","c", "4","d");
    System.out.println("alphaMap- " + alphaMap);
    // Error
    alphaMap.put("5", "e");
  }
}

Output

alphaMap- {2=b, 1=a, 4=d, 3=c}
Exception in thread "main" java.lang.UnsupportedOperationException
 at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:72)
 at java.base/java.util.ImmutableCollections$AbstractImmutableMap.put(ImmutableCollections.java:731)
 at org.netjs.Programs.UnmodifiableMap.main(UnmodifiableMap.java:13)

As you can see trying to modify the immutable Map results in UnsupportedOperationException.

Java Map.ofEntries() method for creating unmodifiable Map

  • Map.ofEntries(Map.Entry<? extends K,? extends V>... entries)- Returns an unmodifiable map containing keys and values extracted from the given entries. The entries themselves are not stored in the map.
import java.util.Map;
import static java.util.Map.entry;

public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = Map.ofEntries(entry("1", "a"), entry("2", "b"),
                     entry("3", "c"), entry("4", "d"));
    System.out.println("alphaMap- " + alphaMap);
  }
}

Output

alphaMap- {3=c, 2=b, 1=a, 4=d}

Map.copyOf() method in Java

If you want to create an unmodifiable Map using an existing collection then you can use copyOf() method.

  • Map.copyOf(Map<? extends K,? extends V> map)- Returns an unmodifiable Map containing the entries of the given Map. The given Map must not be null, and it must not contain any null keys or values. If the given Map is subsequently modified, the returned Map will not reflect such modifications.
public class UnmodifiableMap {
  public static void main(String[] args) {
    Map<String, String> alphaMap = new HashMap<String, String>();
    alphaMap.put("1", "a");
    alphaMap.put("2", "b");
    alphaMap.put("3", "c");
    alphaMap.put("4", "d");
    Map<String, String> aMap = Map.copyOf(alphaMap);
    System.out.println(" aMap- " + aMap);
  }
}

Output

 aMap- {1=a, 4=d, 3=c, 2=b}

That's all for this topic Unmodifiable or Immutable Map in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How to Loop Through a Map in Java
  2. Unmodifiable or Immutable Set in Java
  3. Difference Between HashMap And ConcurrentHashMap in Java
  4. TreeMap in Java With Examples
  5. Difference Between ArrayList And LinkedList in Java

You may also like-

  1. ConcurrentSkipListMap in Java With Examples
  2. Java ReentrantLock With Examples
  3. Java Lambda Expression And Variable Scope
  4. Map Operation in Java Stream API
  5. Java Abstract Class and Abstract Method
  6. Java Program to Convert a File to Byte Array
  7. Autowiring in Spring Using @Autowired and @Inject Annotations
  8. Python count() method - Counting Substrings

No comments:

Post a Comment