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.