🎓 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 ConcurrentHashMap.putIfAbsent() method in Java is used to insert a key-value pair into a ConcurrentHashMap only if the key is not already present in the map.
Table of Contents
- Introduction
putIfAbsentMethod Syntax- Examples
- Adding Entries to a ConcurrentHashMap
- Handling Existing Keys
- Real-World Use Case
- Example: Managing a Student Registration System
- Conclusion
Introduction
The ConcurrentHashMap.putIfAbsent() method is a member of the ConcurrentHashMap class in Java. It allows you to insert a key-value pair into the map only if the key is not already associated with a value. The ConcurrentHashMap class is part of the java.util.concurrent package, designed for high concurrency and scalability.
putIfAbsent() Method Syntax
The syntax for the putIfAbsent method is as follows:
public V putIfAbsent(K key, V value)
- The method takes two parameters:
keyof typeK, which represents the key to be inserted.valueof typeV, which represents the value to be associated with the key.
- The method returns the current value associated with the specified key, or
nullif there was no mapping for the key.
Examples
Adding Entries to a ConcurrentHashMap
The putIfAbsent method can be used to add key-value pairs to a ConcurrentHashMap only if the key is not already present.
Example
import java.util.concurrent.ConcurrentHashMap;
public class PutIfAbsentExample {
public static void main(String[] args) {
// Creating a ConcurrentHashMap with String keys and Integer values
ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();
// Adding entries to the ConcurrentHashMap
people.putIfAbsent("Ravi", 25);
people.putIfAbsent("Priya", 30);
people.putIfAbsent("Vijay", 35);
// Printing the ConcurrentHashMap
System.out.println("ConcurrentHashMap: " + people);
}
}
Output:
ConcurrentHashMap: {Ravi=25, Priya=30, Vijay=35}
Handling Existing Keys
The putIfAbsent method returns the current value associated with the specified key if the key is already present in the ConcurrentHashMap.
Example
import java.util.concurrent.ConcurrentHashMap;
public class ExistingKeyExample {
public static void main(String[] args) {
// Creating a ConcurrentHashMap with String keys and Integer values
ConcurrentHashMap<String, Integer> people = new ConcurrentHashMap<>();
// Adding entries to the ConcurrentHashMap
people.put("Ravi", 25);
people.put("Priya", 30);
// Trying to add a new value for an existing key
Integer existingValue = people.putIfAbsent("Ravi", 40);
// Printing the results
System.out.println("Existing value for 'Ravi': " + existingValue);
System.out.println("ConcurrentHashMap: " + people);
}
}
Output:
Existing value for 'Ravi': 25
ConcurrentHashMap: {Ravi=25, Priya=30}
Real-World Use Case
Example: Managing a Student Registration System
A common real-world use case for ConcurrentHashMap is managing a student registration system where each student can register only once.
Example
import java.util.concurrent.ConcurrentHashMap;
public class StudentRegistration {
public static void main(String[] args) {
// Creating a ConcurrentHashMap to manage student registrations
ConcurrentHashMap<String, String> studentRegistrations = new ConcurrentHashMap<>();
// Adding student registrations to the ConcurrentHashMap
studentRegistrations.putIfAbsent("Ravi", "Registered");
studentRegistrations.putIfAbsent("Priya", "Registered");
studentRegistrations.putIfAbsent("Vijay", "Registered");
// Attempting to register a student who is already registered
String registrationStatus = studentRegistrations.putIfAbsent("Ravi", "Already Registered");
// Printing the results
System.out.println("Registration status for 'Ravi': " + registrationStatus);
System.out.println("Student Registrations: " + studentRegistrations);
}
}
Output:
Registration status for 'Ravi': Registered
Student Registrations: {Ravi=Registered, Priya=Registered, Vijay=Registered}
In this example, ConcurrentHashMap is used to manage student registrations, ensuring that each student can register only once using the putIfAbsent method.
Conclusion
The ConcurrentHashMap.putIfAbsent() method in Java provides a way to insert key-value pairs into a ConcurrentHashMap only if the key is not already present, in a thread-safe manner. By understanding how to use this method, you can efficiently manage collections of key-value pairs in your Java applications, especially in concurrent environments. The method allows you to handle conditional insertions, making it a versatile tool for data management in multi-threaded 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