Member-only story

Stop Map Mayhem! The Key Battle Between putIfAbsent() and computeIfAbsent()

Naveen Metta
2 min readMar 30, 2024

--

credit goes to the owner : https://prepinsta.com/java/hashmap-putifabsent-method/
source : prepinsta.com

Java’s Map interface offers a powerful toolbox for managing key-value pairs. Today, we'll dissect two methods crucial for handling missing keys: putIfAbsent() and computeIfAbsent(). Let's break them down, line by line, for a crystal-clear understanding.

Understanding the Objective:

Both methods share a common goal: adding a key-value pair to the map only if the key doesn’t already exist. This is especially useful to prevent accidentally overwriting existing data. Here’s where they differ:

putIfAbsent(key, value):

  • key: The key you want to check for existence.
  • value: The value you want to add if the key is absent.

Key Points:

  • putIfAbsent() takes the value directly. If the key exists (even if mapped to null), it won't be added, and the existing value is returned.
  • This method is ideal when you have the value ready and simply want to avoid overwrites.

Code Example:

Map<String, Integer> studentAges = new HashMap<>();
Integer age = studentAges.putIfAbsent("John", 25);

if (age == null) {
System.out.println("John's age added successfully!");
} else {
System.out.println("John's age already…

--

--

Naveen Metta
Naveen Metta

Written by Naveen Metta

I'm a Full Stack Developer with 3+ years of experience. feel free to reach out for any help : mettanaveen701@gmail.com

No responses yet