🎓 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
EnumMap is a specialized implementation of the Map interface for use with enum keys. It is a high-performance map implementation that leverages the characteristics of enums to provide efficient and compact maps. This tutorial will cover all methods of EnumMap with examples and outputs, highlighting key points, use cases, best practices, performance considerations, and a real-time example with CRUD operations.Table of Contents
- Introduction
- Key Points
- EnumMap Methods
- put()
- putAll()
- get()
- remove()
- clear()
- size()
- isEmpty()
- containsKey()
- containsValue()
- keySet()
- values()
- entrySet()
- forEach()
- replace()
- compute()
- computeIfAbsent()
- computeIfPresent()
- merge()
- Use Cases
- Best Practices
- Performance Considerations
- Real-time Example with CRUD Operations
- Conclusion
1. Introduction
An EnumMap in Java is a part of the Java Collections Framework and provides a way to manage key-value pairs where the keys are of the enum type. It is found in the java.util package and is designed specifically for use with enum types, providing high performance and low memory consumption.
2. Key Points
EnumMapallows null values but does not allow null keys.- It is highly efficient and compact.
- All keys in an
EnumMapmust come from a single enum type. EnumMapis not synchronized.- It provides constant-time performance for basic operations like put, get, and remove.
3. EnumMap Methods
3.1. put()
The put() method is used to insert key-value pairs into the EnumMap.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
System.out.println(fruits);
}
}
Output:
{APPLE=50, BANANA=30, MANGO=20}
3.2. putAll()
The putAll() method adds all key-value pairs from another map to the EnumMap.
Example:
import java.util.EnumMap;
import java.util.Map;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO, ORANGE
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
Map<Fruit, Integer> moreFruits = new EnumMap<>(Fruit.class);
moreFruits.put(Fruit.MANGO, 20);
moreFruits.put(Fruit.ORANGE, 40);
fruits.putAll(moreFruits);
System.out.println(fruits);
}
}
Output:
{APPLE=50, BANANA=30, MANGO=20, ORANGE=40}
3.3. get()
The get() method retrieves the value associated with the specified key.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
System.out.println(fruits.get(Fruit.BANANA)); // 30
}
}
Output:
30
3.4. remove()
The remove() method removes the key-value pair associated with the specified key.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
fruits.remove(Fruit.BANANA);
System.out.println(fruits); // {APPLE=50, MANGO=20}
}
}
Output:
{APPLE=50, MANGO=20}
3.5. clear()
The clear() method removes all key-value pairs from the EnumMap.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
fruits.clear();
System.out.println(fruits); // {}
}
}
Output:
{}
3.6. size()
The size() method returns the number of key-value pairs in the EnumMap.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
System.out.println(fruits.size()); // 3
}
}
Output:
3
3.7. isEmpty()
The isEmpty() method checks if the EnumMap is empty.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
System.out.println(fruits.isEmpty()); // true
fruits.put(Fruit.APPLE, 50);
System.out.println(fruits.isEmpty()); // false
}
}
Output:
true
false
3.8. containsKey()
The containsKey() method checks if the EnumMap contains a specified key.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
System.out.println(fruits.containsKey(Fruit.BANANA)); // true
System.out.println(fruits.containsKey(Fruit.MANGO)); // false
}
}
Output:
true
false
3.9. containsValue()
The containsValue() method checks if the EnumMap contains a specified value.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
System.out.println(fruits.containsValue(30)); // true
System.out.println(fruits.containsValue(20)); // false
}
}
Output:
true
false
3.10. keySet()
The keySet() method returns a set view of the keys contained in the EnumMap.
Example:
import java.util.EnumMap;
import java.util.Set;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
Set<Fruit> keys = fruits.keySet();
System.out.println(keys); // [APPLE, BANANA, MANGO]
}
}
Output:
[APPLE, BANANA, MANGO]
3.11. values()
The values() method returns a collection view of the values contained in the EnumMap.
Example:
import java.util.EnumMap;
import java.util.Collection;
public class EnumMapExample {
enum Fruit {
APP
LE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
Collection<Integer> values = fruits.values();
System.out.println(values); // [50, 30, 20]
}
}
Output:
[50, 30, 20]
3.12. entrySet()
The entrySet() method returns a set view of the mappings contained in the EnumMap.
Example:
import java.util.EnumMap;
import java.util.Set;
import java.util.Map.Entry;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
Set<Entry<Fruit, Integer>> entries = fruits.entrySet();
for (Entry<Fruit, Integer> entry : entries) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
}
Output:
APPLE = 50
BANANA = 30
MANGO = 20
3.13. forEach()
The forEach() method performs the given action for each entry in the EnumMap.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.put(Fruit.MANGO, 20);
fruits.forEach((key, value) -> System.out.println(key + " = " + value));
}
}
Output:
APPLE = 50
BANANA = 30
MANGO = 20
3.14. replace()
The replace() method replaces the entry for the specified key only if it is currently mapped to some value.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.replace(Fruit.BANANA, 40);
System.out.println(fruits); // {APPLE=50, BANANA=40, MANGO=20}
}
}
Output:
{APPLE=50, BANANA=40, MANGO=20}
3.15. compute()
The compute() method computes a new mapping for the specified key and its current mapped value (or null if there is no current mapping).
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.compute(Fruit.BANANA, (key, value) -> (value == null) ? 40 : value + 10);
System.out.println(fruits); // {APPLE=50, BANANA=40, MANGO=20}
}
}
Output:
{APPLE=50, BANANA=40, MANGO=20}
3.16. computeIfAbsent()
The computeIfAbsent() method computes a mapping for the specified key if it is not already present.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.computeIfAbsent(Fruit.MANGO, key -> 20);
System.out.println(fruits); // {APPLE=50, BANANA=30, MANGO=20}
}
}
Output:
{APPLE=50, BANANA=30, MANGO=20}
3.17. computeIfPresent()
The computeIfPresent() method computes a new mapping for the specified key if it is currently present.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.computeIfPresent(Fruit.BANANA, (key, value) -> value + 10);
System.out.println(fruits); // {APPLE=50, BANANA=40, MANGO=20}
}
}
Output:
{APPLE=50, BANANA=40, MANGO=20}
3.18. merge()
The merge() method merges the specified value with the existing value associated with the specified key.
Example:
import java.util.EnumMap;
public class EnumMapExample {
enum Fruit {
APPLE, BANANA, MANGO
}
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruits = new EnumMap<>(Fruit.class);
fruits.put(Fruit.APPLE, 50);
fruits.put(Fruit.BANANA, 30);
fruits.merge(Fruit.BANANA, 20, (oldValue, newValue) -> oldValue + newValue);
System.out.println(fruits); // {APPLE=50, BANANA=50, MANGO=20}
}
}
Output:
{APPLE=50, BANANA=50, MANGO=20}
4. Use Cases
- Efficient mappings: Storing key-value pairs with enum keys efficiently.
- Configuration settings: Storing application settings as key-value pairs with enum keys.
- Switch-case replacement: Using
EnumMapas a replacement for switch-case statements for better performance and readability.
5. Best Practices
- Use appropriate initial capacity: If the size of the map is known in advance, setting an initial capacity can improve performance.
- Use immutable keys: Using mutable objects as keys can lead to unpredictable behavior.
- Avoid frequent resizing: Adding elements frequently can cause resizing. Consider setting an appropriate initial capacity.
6. Performance Considerations
- Constant-time performance:
EnumMapprovides constant-time performance for basic operations like put, get, and remove. - Memory usage:
EnumMapis highly efficient and compact, making it ideal for use with enum keys. - Thread safety:
EnumMapis not synchronized. UseCollections.synchronizedMap()if thread safety is needed.
7. Real-time Example with CRUD Operations
Managing a Fruit Inventory:
Fruit.java:
public enum Fruit {
APPLE, BANANA, MANGO
}
Main.java:
import java.util.EnumMap;
public class Main {
public static void main(String[] args) {
EnumMap<Fruit, Integer> fruitInventory = new EnumMap<>(Fruit.class);
// Create
fruitInventory.put(Fruit.APPLE, 50);
fruitInventory.put(Fruit.BANANA, 30);
fruitInventory.put(Fruit.MANGO, 20);
// Read
for (EnumMap.Entry<Fruit, Integer> entry : fruitInventory.entrySet()) {
System.out.println("Fruit: " + entry.getKey() + ", Quantity: " + entry.getValue());
}
// Update
fruitInventory.put(Fruit.BANANA, 40);
System.out.println("After Update:");
for (EnumMap.Entry<Fruit, Integer> entry : fruitInventory.entrySet()) {
System.out.println("Fruit: " + entry.getKey() + ", Quantity: " + entry.getValue());
}
// Delete
fruitInventory.remove(Fruit.APPLE);
System.out.println("After Deletion:");
for (EnumMap.Entry<Fruit, Integer> entry : fruitInventory.entrySet()) {
System.out.println("Fruit: " + entry.getKey() + ", Quantity: " + entry.getValue());
}
}
}
Output:
Fruit: APPLE, Quantity: 50
Fruit: BANANA, Quantity: 30
Fruit: MANGO, Quantity: 20
After Update:
Fruit: BANANA, Quantity: 40
Fruit: MANGO, Quantity: 20
After Deletion:
Fruit: BAN
ANA, Quantity: 40
Fruit: MANGO, Quantity: 20
8. Conclusion
The EnumMap class in Java is a powerful class for managing key-value pairs with enum keys. By understanding its methods, use cases, and best practices, you can effectively utilize EnumMap in your Java applications. This tutorial covers the essential methods with examples and demonstrates a real-time example with CRUD operations.
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