🎓 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
The EnumMap.getOrDefault(Object key, V defaultValue) method in Java is used to return the value associated with the specified key, or a default value if the key is not present in the map. This guide will cover the method's usage with examples, and we will also cover a real-world use case to show how EnumMap.getOrDefault() can be used effectively.
Table of Contents
- Introduction
getOrDefaultMethod Syntax- Examples
- Basic Usage of
getOrDefaultMethod - Handling Non-Existent Keys with Default Values
- Basic Usage of
- Real-World Use Case
- Example: Retrieving Default Task for Unassigned Days
- Conclusion
Introduction
The EnumMap.getOrDefault(Object key, V defaultValue) method is a member of the EnumMap class in Java. It allows you to retrieve the value associated with the specified key, or return a default value if the key is not present in the map.
getOrDefault() Method Syntax
The syntax for the getOrDefault method is as follows:
public V getOrDefault(Object key, V defaultValue)
- Parameters:
key: The key whose associated value is to be returned.defaultValue: The value to be returned if the key is not found in the map.
- Returns: The value associated with the specified key, or
defaultValueif the key is not found.
Examples
Basic Usage of getOrDefault Method
The getOrDefault method can be used to retrieve a value associated with a key or a default value if the key is not present in the EnumMap.
Example
import java.util.EnumMap;
public class EnumMapGetOrDefaultExample {
// Define an enum representing days of the week
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static void main(String[] args) {
// Create an EnumMap with Day as key and String as value
EnumMap<Day, String> tasks = new EnumMap<>(Day.class);
// Adding entries to the EnumMap
tasks.put(Day.MONDAY, "Go to gym");
tasks.put(Day.TUESDAY, "Attend meeting");
// Using getOrDefault to retrieve a value or a default value
String taskMonday = tasks.getOrDefault(Day.MONDAY, "No task assigned");
String taskSunday = tasks.getOrDefault(Day.SUNDAY, "No task assigned");
// Printing the results
System.out.println("Task for Monday: " + taskMonday);
System.out.println("Task for Sunday: " + taskSunday);
}
}
Output:
Task for Monday: Go to gym
Task for Sunday: No task assigned
Handling Non-Existent Keys with Default Values
You can use the getOrDefault method to handle cases where a key is not present in the EnumMap, providing a default value instead.
Example
import java.util.EnumMap;
public class EnumMapDefaultExample {
// Define an enum representing months of the year
enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
public static void main(String[] args) {
// Create an EnumMap with Month as key and String as value
EnumMap<Month, String> holidays = new EnumMap<>(Month.class);
// Adding entries to the EnumMap
holidays.put(Month.JANUARY, "New Year's Day");
holidays.put(Month.DECEMBER, "Christmas Day");
// Using getOrDefault to handle non-existent keys
String holidayMarch = holidays.getOrDefault(Month.MARCH, "No holiday");
String holidayDecember = holidays.getOrDefault(Month.DECEMBER, "No holiday");
// Printing the results
System.out.println("Holiday in March: " + holidayMarch);
System.out.println("Holiday in December: " + holidayDecember);
}
}
Output:
Holiday in March: No holiday
Holiday in December: Christmas Day
Real-World Use Case
Example: Retrieving Default Task for Unassigned Days
A common real-world use case for EnumMap.getOrDefault() is retrieving default tasks for days where no specific task has been assigned.
Example
import java.util.EnumMap;
public class TaskAssigner {
// Define an enum representing days of the week
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
public static void main(String[] args) {
// Create an EnumMap to manage tasks for each day
EnumMap<Day, String> tasks = new EnumMap<>(Day.class);
// Adding tasks for specific days
tasks.put(Day.MONDAY, "Go to gym");
tasks.put(Day.TUESDAY, "Attend meeting");
tasks.put(Day.FRIDAY, "Project presentation");
// Using getOrDefault to retrieve tasks for all days, with a default task
for (Day day : Day.values()) {
String task = tasks.getOrDefault(day, "No specific task assigned");
System.out.println("Task for " + day + ": " + task);
}
}
}
Output:
Task for MONDAY: Go to gym
Task for TUESDAY: Attend meeting
Task for WEDNESDAY: No specific task assigned
Task for THURSDAY: No specific task assigned
Task for FRIDAY: Project presentation
Task for SATURDAY: No specific task assigned
Task for SUNDAY: No specific task assigned
In this example, EnumMap.getOrDefault() is used to retrieve tasks for all days of the week, providing a default task for days that do not have specific tasks assigned.
Conclusion
The EnumMap.getOrDefault(Object key, V defaultValue) method in Java provides a way to retrieve the value associated with a specified key or return a default value if the key is not found. By understanding how to use this method, you can efficiently handle cases where keys may not be present in the map and provide meaningful default values. This method allows you to manage and utilize the entries in an EnumMap, making it a versatile tool for managing data in various scenarios.
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