Java Map copyOf()

In this guide, you will learn about the Map copyOf() method in Java programming and how to use it with an example.

1. Map copyOf() Method Overview

Definition:

The copyOf() method in the Map interface of Java is a static method used to create an unmodifiable Map containing the mappings of the given Map.

Syntax:

static <K, V> Map<K, V> copyOf(Map<? extends K, ? extends V> map)

Parameters:

- map: the map from which mappings are to be copied.

Key Points:

- The returned Map is unmodifiable, meaning any attempt to modify it will result in an UnsupportedOperationException.

- If the provided Map is modified after the new Map is created, the returned Map does not reflect such modifications.

- The method throws a NullPointerException if the given map, any of its keys, or any of its values are null.

- The copyOf() method has been available since Java 10.

2. Map copyOf() Method Example

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

public class MapCopyOfExample {
    public static void main(String[] args) {
        Map<String, Integer> originalMap = new HashMap<>();
        originalMap.put("Apple", 1);
        originalMap.put("Banana", 2);
        originalMap.put("Cherry", 3);

        // Creating an unmodifiable copy of the original map
        Map<String, Integer> copiedMap = Map.copyOf(originalMap);

        System.out.println("Original Map: " + originalMap);
        System.out.println("Copied Map: " + copiedMap);

        // Attempting to modify the copied map will throw UnsupportedOperationException
        try {
            copiedMap.put("Date", 4);
        } catch (UnsupportedOperationException e) {
            System.out.println("Exception: " + e.getMessage());
        }
    }
}

Output:

Original Map: {Banana=2, Cherry=3, Apple=1}
Copied Map: {Banana=2, Cherry=3, Apple=1}
Exception: UnsupportedOperationException

Explanation:

In this example, a HashMap named originalMap is created and populated with three mappings. 

The Map.copyOf() method is then used to create an unmodifiable copy of originalMap, named copiedMap. The contents of both the original and copied maps are printed to the console, showing that they contain the same mappings. 

An attempt to add a new mapping to copiedMap is then made, demonstrating that the copied map is unmodifiable. This attempt results in an UnsupportedOperationException being thrown and caught, and the exception's message is printed to the console.

Comments