WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Intermediate · question 39 of 100

How do you create an unmodifiable Map in Java Collections?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

In Java Collections, we can create an unmodifiable Map using the Collections.unmodifiableMap() method. This method returns an unmodifiable view of the specified Map. Any attempt to modify the returned map will result in an UnsupportedOperationException.

Here’s an example code that demonstrates how to create an unmodifiable Map:

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

public class Example {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "apple");
        map.put(2, "banana");
        map.put(3, "cherry");
    
        Map<Integer, String> unmodifiableMap = Collections.unmodifiableMap(map);
    
        // Try to modify the unmodifiable map
        try {
            unmodifiableMap.put(4, "date");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify unmodifiable map");
        }
    
        // Print the unmodifiable map
        System.out.println("Unmodifiable map:");
        for (Map.Entry<Integer, String> entry : unmodifiableMap.entrySet()) {
            System.out.println(entry.getKey() + " = " + entry.getValue());
        }
    }
}

In this example, we first create a HashMap and add three key-value pairs to it. We then create an unmodifiable view of the map using the Collections.unmodifiableMap() method.

We then try to modify the unmodifiable map by adding a new key-value pair, which results in an UnsupportedOperationException. Finally, we iterate through the entries of the unmodifiable map and print them to the console.

Note that while the returned map is unmodifiable, the underlying original map can still be modified, so it is important to use this method only when it is necessary to create an immutable view of the original map.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics