🎓 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 (178K+ 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.ofandMap.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.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment