Java Map copyOf()

Introduction

The Map.copyOf() method was introduced in Java 10 as a part of the Java Collections Framework. It is used to create an unmodifiable copy of an existing Map. This method ensures that the resulting Map cannot be modified, meaning no new entries can be added, and no existing entries can be removed or updated. Any attempt to modify the Map will throw an UnsupportedOperationException.

Additionally, the Map.copyOf() method does not accept null keys or values. If the source Map contains null, a NullPointerException will be thrown.

Solution Steps

  1. Create a Mutable Map: Start by creating a mutable Map (e.g., HashMap or TreeMap).
  2. Use Map.copyOf(): Use the Map.copyOf() method to create an unmodifiable copy of the original Map.
  3. Attempt Modifications: Try to modify the unmodifiable map and observe the UnsupportedOperationException.
  4. Display the Map: Print the original and copied Map to verify the contents.

Java Program

Example 1: Copying a Map of Strings

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

public class MapCopyOfExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable map of strings
        Map<String, String> originalMap = new HashMap<>();
        originalMap.put("Java", "A programming language");
        originalMap.put("Python", "Another programming language");
        originalMap.put("JavaScript", "Web programming language");

        // Step 2: Create an unmodifiable copy of the map
        Map<String, String> unmodifiableMap = Map.copyOf(originalMap);

        // Step 3: Display the unmodifiable map
        System.out.println("Unmodifiable Map: " + unmodifiableMap);

        // Step 4: Attempt to modify the unmodifiable map (This will throw an exception)
        try {
            unmodifiableMap.put("C++", "Yet another language");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable map");
        }
    }
}

Output

Unmodifiable Map: {Java=A programming language, Python=Another programming language, JavaScript=Web programming language}
Error: Cannot modify an unmodifiable map

Explanation

Step 1: Create a Mutable Map

We first create a mutable HashMap and populate it with some key-value pairs:

Map<String, String> originalMap = new HashMap<>();
originalMap.put("Java", "A programming language");
originalMap.put("Python", "Another programming language");
originalMap.put("JavaScript", "Web programming language");

This map contains three key-value pairs representing different programming languages.

Step 2: Create an Unmodifiable Copy Using Map.copyOf()

Next, we use Map.copyOf() to create an unmodifiable copy of originalMap:

Map<String, String> unmodifiableMap = Map.copyOf(originalMap);

This returns an unmodifiable copy of originalMap. Any attempt to modify this map will result in an UnsupportedOperationException.

Step 3: Display the Unmodifiable Map

The program then prints the contents of unmodifiableMap:

System.out.println("Unmodifiable Map: " + unmodifiableMap);

Output:

Unmodifiable Map: {Java=A programming language, Python=Another programming language, JavaScript=Web programming language}

Step 4: Attempt to Modify the Unmodifiable Map

Finally, we attempt to add a new entry to unmodifiableMap, which causes an UnsupportedOperationException:

try {
    unmodifiableMap.put("C++", "Yet another language");
} catch (UnsupportedOperationException e) {
    System.out.println("Error: Cannot modify an unmodifiable map");
}

Output:

Error: Cannot modify an unmodifiable map

Example 2: Copying a Map of Integers

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

public class MapCopyOfIntegerExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable map of integers
        Map<Integer, String> originalMap = new HashMap<>();
        originalMap.put(1, "One");
        originalMap.put(2, "Two");
        originalMap.put(3, "Three");

        // Step 2: Create an unmodifiable copy of the map
        Map<Integer, String> unmodifiableMap = Map.copyOf(originalMap);

        // Step 3: Display the unmodifiable map
        System.out.println("Unmodifiable Integer Map: " + unmodifiableMap);

        // Step 4: Attempt to modify the unmodifiable map (This will throw an exception)
        try {
            unmodifiableMap.put(4, "Four");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable map");
        }
    }
}

Output

Unmodifiable Integer Map: {1=One, 2=Two, 3=Three}
Error: Cannot modify an unmodifiable map

Explanation

  • Original Map: A mutable map with integer keys and string values (1 -> "One", 2 -> "Two", 3 -> "Three").
  • Unmodifiable Map: Map.copyOf() creates an unmodifiable copy of the map.
  • Modification Attempt: An attempt to add a new entry results in an UnsupportedOperationException.

Example 3: Copying a Map of Custom Objects

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

public class MapCopyOfCustomObjectExample {
    public static void main(String[] args) {
        // Step 1: Create a mutable map of Employee objects
        Map<String, Employee> originalMap = new HashMap<>();
        originalMap.put("Ravi", new Employee("Ravi", 30));
        originalMap.put("Amit", new Employee("Amit", 28));
        originalMap.put("Pooja", new Employee("Pooja", 35));

        // Step 2: Create an unmodifiable copy of the map
        Map<String, Employee> unmodifiableMap = Map.copyOf(originalMap);

        // Step 3: Display the unmodifiable map
        System.out.println("Unmodifiable Employee Map: " + unmodifiableMap);

        // Step 4: Attempt to modify the unmodifiable map (This will throw an exception)
        try {
            unmodifiableMap.put("Neha", new Employee("Neha", 27));
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an unmodifiable map");
        }
    }
}

class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return name + " (" + age + ")";
    }
}

Output

Unmodifiable Employee Map: {Ravi=Ravi (30), Amit=Amit (28), Pooja=Pooja (35)}
Error: Cannot modify an unmodifiable map

Explanation

  • Original Map: A map where each key is a string (employee name) and each value is an Employee object.
  • Unmodifiable Map: Map.copyOf() creates an immutable version of the original map.
  • Modification Attempt: Trying to add a new entry throws an UnsupportedOperationException.

Conclusion

The Map.copyOf() method in Java 10 provides a simple way to create unmodifiable maps from existing maps. The resulting map is immutable and does not allow any modification attempts, which makes it useful for creating read-only views of data. The method works with maps containing various types, including strings, integers, and custom objects. It also does not allow null keys or values, throwing a NullPointerException if the original map contains null.

Comments