🎓 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
HashMap.computeIfAbsent() method in Java is used to compute a value for a specified key if the key is not already associated with a value (or is mapped to null). This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.Table of Contents
- Introduction
computeIfAbsentMethod Syntax- Examples
- Adding an Entry If Absent in a HashMap
- Real-World Use Case: Initializing Default Configurations
- Conclusion
Introduction
The HashMap.computeIfAbsent() method is a member of the HashMap class in Java. It allows you to compute and insert a value for a specified key only if the key is not already associated with a value or is mapped to null. This is useful for lazy initialization and for avoiding unnecessary computations.
computeIfAbsent() Method Syntax
The syntax for the computeIfAbsent method is as follows:
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
- The method takes two parameters:
keyof typeK, which represents the key whose value is to be computed and inserted if absent.mappingFunctionof typeFunction<? super K, ? extends V>, which represents the function to compute a value.
- The method returns the current (existing or computed) value associated with the specified key, or
nullif the computed value isnull.
Examples
Adding an Entry If Absent in a HashMap
The computeIfAbsent method can be used to add a key-value pair to a HashMap only if the key is not already present.
Example with Lambda Expression
import java.util.HashMap;
import java.util.function.Function;
public class ComputeIfAbsentExample {
public static void main(String[] args) {
// Creating a HashMap with String keys and Integer values
HashMap<String, Integer> people = new HashMap<>();
// Adding entries to the HashMap
people.put("Ravi", 25);
people.put("Priya", 30);
// Using computeIfAbsent method to add "Vijay" if absent
people.computeIfAbsent("Vijay", key -> 35);
// Using computeIfAbsent method to add "Amit" if absent
people.computeIfAbsent("Amit", key -> 40);
// Printing the updated HashMap
System.out.println("Updated HashMap: " + people);
}
}
Output:
Updated HashMap: {Ravi=25, Priya=30, Vijay=35, Amit=40}
Real-World Use Case: Initializing Default Configurations
In a real-world scenario, you might use the computeIfAbsent method to initialize default configurations for a user if they are not already set.
Example with Lambda Expression
import java.util.HashMap;
import java.util.function.Function;
public class DefaultConfigurations {
public static void main(String[] args) {
// Creating a HashMap with String keys (configuration names) and String values (configuration values)
HashMap<String, String> configurations = new HashMap<>();
// Adding some configurations to the HashMap
configurations.put("theme", "dark");
configurations.put("fontSize", "medium");
// Using computeIfAbsent method to set default language if absent
configurations.computeIfAbsent("language", key -> "English");
// Using computeIfAbsent method to set default time zone if absent
configurations.computeIfAbsent("timezone", key -> "UTC");
// Printing the updated configurations
System.out.println("Updated Configurations: " + configurations);
}
}
Output:
Updated Configurations: {theme=dark, fontSize=medium, language=English, timezone=UTC}
Conclusion
The HashMap.computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) method in Java provides a way to compute and insert a value for a specified key only if the key is not already associated with a value or is mapped to null. By understanding how to use this method, you can efficiently manage default values, lazy initialization, and conditional inserts in your map. This method is useful in various scenarios, such as initializing default configurations, managing cache entries, and handling missing data in collections.
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