How do you convert an unmodifiable map to a modifiable map ?

Convert an unmodifiable map to a modifiable map

An “Unmodifiable Map” in Java refers to a map data structure that is designed to be immutable, meaning its contents cannot be changed after it is initially created.

It is a map implementation that prevents modifications such as adding, removing, or updating entries once the map is constructed.

This can be useful in scenarios where you want to ensure that the map’s contents remain constant and cannot be accidentally modified by other parts of the code.

In Java, you can create an unmodifiable map using the Collections.unmodifiableMap() method.

This method takes an existing map as an argument and returns a new map that wraps the original map, preventing modifications through the standard map manipulation methods.

Example:

Here’s an example of how you can create and use an unmodifiable map in Java:

import java.util.*;

public class UnmodifiableMapExample {
    public static void main(String[] args) {
        // Create a regular mutable map
        Map<String, Integer> mutableMap = new HashMap<>();
        mutableMap.put("one", 1);
        mutableMap.put("two", 2);
        mutableMap.put("three", 3);

        // Create an unmodifiable map based on the mutable map
        Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(mutableMap);

        // This will throw an UnsupportedOperationException
        // unmodifiableMap.put("four", 4);

        // You can still read values from the unmodifiable map
        System.out.println("Value for 'one': " + unmodifiableMap.get("one"));

        // Iterating through the unmodifiable map
        for (Map.Entry<String, Integer> entry : unmodifiableMap.entrySet()) {
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Explanation:

In this example, the unmodifiableMap created using Collections.unmodifiableMap() prevents modifications to its content.

Any attempt to modify the unmodifiable map will result in an UnsupportedOperationException.

Unmodifiable maps are handy in scenarios where you want to provide read-only access to specific data structures, ensuring that the data remains consistent throughout the program’s lifetime.

Leave a Comment