📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this article, we will discuss how to create a read-only Map
in Java. We will cover different approaches to achieve this using various classes and methods provided by the Java Collections Framework.
Table of Contents
- Introduction
- Using
Collections.unmodifiableMap
- Using Java 9
Map.of
andMap.copyOf
- Complete Example
- Conclusion
Introduction
A read-only Map
is a map that does not support any modification operations like put
, remove
, or clear
. This is useful when you want to provide read-only access to a Map
to ensure that it cannot be altered.
Using Collections.unmodifiableMap
The Collections.unmodifiableMap
method wraps a given map and returns an unmodifiable view of it. Any attempt to modify the map will result in an UnsupportedOperationException
.
Example
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class UnmodifiableMapExample { public static void main(String[] args) { Map<String, String> originalMap = new HashMap<>(); originalMap.put("key1", "value1"); originalMap.put("key2", "value2"); Map<String, String> readOnlyMap = Collections.unmodifiableMap(originalMap); System.out.println("Read-Only Map: " + readOnlyMap); // Attempting to modify the map will throw UnsupportedOperationException try { readOnlyMap.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map: " + e.getMessage()); } } }
Output:
Read-Only Map: {key1=value1, key2=value2} Cannot modify the read-only map: null
Using Java 9 Map.of and Map.copyOf
Java 9 introduced new factory methods for creating immutable maps. These maps are inherently read-only and any attempt to modify them will result in an UnsupportedOperationException
.
Using Map.of
The Map.of
method can be used to create a small read-only map with up to 10 entries.
Example
import java.util.Map; public class MapOfExample { public static void main(String[] args) { Map<String, String> readOnlyMap = Map.of( "key1", "value1", "key2", "value2" ); System.out.println("Read-Only Map: " + readOnlyMap); // Attempting to modify the map will throw UnsupportedOperationException try { readOnlyMap.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map: " + e.getMessage()); } } }
Output:
Read-Only Map: {key1=value1, key2=value2} Cannot modify the read-only map: null
Using Map.copyOf
The Map.copyOf
method can be used to create an unmodifiable copy of an existing map.
Example
import java.util.HashMap; import java.util.Map; public class MapCopyOfExample { public static void main(String[] args) { Map<String, String> originalMap = new HashMap<>(); originalMap.put("key1", "value1"); originalMap.put("key2", "value2"); Map<String, String> readOnlyMap = Map.copyOf(originalMap); System.out.println("Read-Only Map: " + readOnlyMap); // Attempting to modify the map will throw UnsupportedOperationException try { readOnlyMap.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map: " + e.getMessage()); } } }
Output:
Read-Only Map: {key1=value1, key2=value2} Cannot modify the read-only map: null
Complete Example
Here's a complete example that demonstrates all methods for creating a read-only map in Java.
import java.util.Collections; import java.util.HashMap; import java.util.Map; public class ReadOnlyMapExample { public static void main(String[] args) { // Using Collections.unmodifiableMap Map<String, String> originalMap = new HashMap<>(); originalMap.put("key1", "value1"); originalMap.put("key2", "value2"); Map<String, String> readOnlyMap1 = Collections.unmodifiableMap(originalMap); System.out.println("Read-Only Map (unmodifiableMap): " + readOnlyMap1); try { readOnlyMap1.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map (unmodifiableMap): " + e.getMessage()); } // Using Map.of Map<String, String> readOnlyMap2 = Map.of( "key1", "value1", "key2", "value2" ); System.out.println("Read-Only Map (Map.of): " + readOnlyMap2); try { readOnlyMap2.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map (Map.of): " + e.getMessage()); } // Using Map.copyOf Map<String, String> readOnlyMap3 = Map.copyOf(originalMap); System.out.println("Read-Only Map (Map.copyOf): " + readOnlyMap3); try { readOnlyMap3.put("key3", "value3"); } catch (UnsupportedOperationException e) { System.out.println("Cannot modify the read-only map (Map.copyOf): " + e.getMessage()); } } }
Output:
Read-Only Map (unmodifiableMap): {key1=value1, key2=value2} Cannot modify the read-only map (unmodifiableMap): null Read-Only Map (Map.of): {key1=value1, key2=value2} Cannot modify the read-only map (Map.of): null Read-Only Map (Map.copyOf): {key1=value1, key2=value2} Cannot modify the read-only map (Map.copyOf): null
Conclusion
Creating a read-only map in Java can be done using various approaches. The Collections.unmodifiableMap
method wraps an existing map to provide a read-only view, while Java 9's Map.of
and Map.copyOf
methods provide a simpler and more concise way to create immutable maps. This guide provided examples to demonstrate each approach, allowing you to choose the method that best fits your needs.
Comments
Post a Comment
Leave Comment