What is the getOrDefault method for HashMaps in Java?
What is the header for the getOrDefault() method?
The regular header for the getOrDefault method is defined as follows.hashMap.getOrDefault(Object key, Object defaultValue)
Parameters Passed
The method header takes two arguments. They are enlisted along with their data types below.- The first one is the specified key of the Object type.
- The other Object type is parameter is defaultValue passed for the object key as the method argument.
Working of the getOrDefault() method
You can understand the working of the getOrDefault() method in the following two simple steps.- The getOrDefault(key, defaultValue) is designed to get the value corresponding to the key in the HashMap.
- If there is a value associated with the key, then that value is returned. On the other hand, if the value is not available, then the defaultValue passed as a parameter to this method is returned.
Example 1
import java.util.HashMap;
public class Driver1{
public static void main(String[] args) {
// Declare a HashMap
HashMap weekDays = new HashMap<>();
// Add data to the HashMap
weekDays.put("Monday", "Working Day");
weekDays.put("Tuesday", "Working Day");
weekDays.put("Wednesday", "Working Day");
weekDays.put("Thursday", "Working Day");
weekDays.put("Friday", "Working Day");
weekDays.put("Saturday", "Off Day");
weekDays.put("Sunday", "Off Day");
// Print the data in the HashMap
System.out.println("Working Schedule : " + weekDays + "\n");
// Check if the given key is present in the Map
// IF yes, its value will be returned
String sunday = weekDays.getOrDefault("Sunday", "No Announcements Yet.");
System.out.println("Is Sunday a working day? " + sunday);
// IF not, the default value passed will be returned
String christmas = weekDays.getOrDefault("Christmas", "National Holiday");
System.out.println("Is Christmas a working day? " + christmas);
// Key not present in the HashMap
// Default Value returned
String easter = weekDays.getOrDefault("Easter", "National Holiday");
System.out.println("Is Easter a working day? " + easter);
}
}
Output
Working Schedule : {Monday=Working Day, Thursday=Working Day, Friday=Working Day, Sunday=Off Day, Wednesday=Working Day, Tuesday=Working Day, Saturday=Off Day}
Is Sunday a working day? Off Day
Is Christmas a working day? National Holiday
Is Easter a working day? National Holiday
Why use the getOrDefault() and not get() method?
The simple get() method in Java is used to get the value of the requested key in the HashMap. If the key is found, the value is returned. In case the key is not found, “null” is returned. The getOrDefault() method is preferred over the simple get method when a default value is expected to return. Here’s a simple example for your understanding.Example 2
import java.util.HashMap;
public class Driver2{
public static void main(String[] args) {
HashMap<Object, Boolean> holidays = new HashMap<>();
// Add data to the HashMap
holidays.put("Saturday", true);
holidays.put("Sunday", true);
// Print the data in the HashMap
System.out.println("Holidays: " + holidays + "\n");
// Key not present, default value returned
Object christmas = holidays.getOrDefault("Christmas", true);
System.out.println("Is Christmas a holiday? " + christmas);
// Key not present, null returned
christmas = holidays.get("Christmas");
System.out.println("Is Christmas a holiday? " + christmas);
}
}
Output
Holidays: {Sunday=true, Saturday=true}
Is Christmas a holiday? true
Is Christmas a holiday? null
You can see the difference between the getOrDefault and the get method. As printed in the output, the first method returns the default value if the key is not found while the latter returns null.Diverse Practical Examples of Using getOrDefault()
1. Default Values for Missing Configuration Settings
Consider an application where configuration settings are stored in a HashMap
. The getOrDefault
method can provide default values for missing settings:
import java.util.HashMap;
public class ConfigExample {
public static void main(String[] args) {
HashMap config = new HashMap<>();
config.put("theme", "dark");
config.put("language", "en");
String theme = config.getOrDefault("theme", "light");
String fontSize = config.getOrDefault("fontSize", "12px");
System.out.println("Theme: " + theme);
System.out.println("Font Size: " + fontSize);
}
}
Output:
Theme: dark Font Size: 12px
2. Counting Word Frequencies
Using getOrDefault
to count word occurrences in a string:
import java.util.HashMap;
public class WordFrequencyExample {
public static void main(String[] args) {
String text = "apple banana apple orange banana apple";
String[] words = text.split(" ");
HashMap wordCount = new HashMap<>();
for (String word : words) {
wordCount.put(word, wordCount.getOrDefault(word, 0) + 1);
}
System.out.println(wordCount);
}
}
Output:
{apple=3, banana=2, orange=1}
3. Default Grades for Students
Providing default grades for students not in the record:
import java.util.HashMap;
public class DefaultGradeExample {
public static void main(String[] args) {
HashMap grades = new HashMap<>();
grades.put("Alice", 85);
grades.put("Bob", 92);
int charlieGrade = grades.getOrDefault("Charlie", 75);
System.out.println("Charlie's grade: " + charlieGrade);
}
}
Using getOrDefault() with Different Data Structures
Example with Properties
The Properties
class is another commonly used data structure where getOrDefault
can be applied:
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("app.name", "DemoApp");
String appName = properties.getOrDefault("app.name", "UnknownApp").toString();
String version = properties.getOrDefault("app.version", "1.0").toString();
System.out.println("App Name: " + appName);
System.out.println("App Version: " + version);
}
}
Output:
App Name: DemoApp App Version: 1.0
Using getOrDefault() with Non-String Keys and Values
Example with Integer Keys and Custom Object Values
The getOrDefault
method is not limited to String keys and values. Here is an example using Integer keys and custom object values:
import java.util.HashMap;
class Product {
String name;
double price;
Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return name + " ($" + price + ")";
}
}
public class CustomObjectExample {
public static void main(String[] args) {
HashMap products = new HashMap<>();
products.put(1, new Product("Laptop", 999.99));
Product defaultProduct = new Product("Unknown", 0.0);
Product product = products.getOrDefault(2, defaultProduct);
System.out.println("Product: " + product);
}
}
Output:
Product: Unknown ($0.0)