Java HashMap putIfAbsent() Method

The HashMap.putIfAbsent(K key, V value) method in Java is used to insert a key-value pair into a HashMap only if the specified key is not already associated with a value. This guide will cover the method's usage, explain how it works, and provide examples to demonstrate its functionality.

Table of Contents

  1. Introduction
  2. putIfAbsent Method Syntax
  3. Examples
    • Inserting Entries Only If Key Is Absent
    • Real-World Use Case: Default Settings Initialization
  4. Conclusion

Introduction

The putIfAbsent() method is a member of the HashMap class in Java. It allows you to add a key-value pair to the map only if the key is not already associated with a value. This can be useful for ensuring that a key does not overwrite an existing value.

putIfAbsent() Method Syntax

The syntax for the putIfAbsent method is as follows:

public V putIfAbsent(K key, V value)
  • The method takes two parameters:
    • key of type K, which represents the key to be added if it is not already present.
    • value of type V, which represents the value to be associated with the key if the key is not already present.
  • The method returns the current value associated with the specified key, or null if there was no mapping for the key.

Examples

Inserting Entries Only If Key Is Absent

The putIfAbsent method can be used to insert key-value pairs into a HashMap only if the key is not already present.

Example

import java.util.HashMap;

public class PutIfAbsentExample {
    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 putIfAbsent method
        Integer previousValue1 = people.putIfAbsent("Ravi", 28); // Key "Ravi" already exists
        Integer previousValue2 = people.putIfAbsent("Vijay", 35); // Key "Vijay" does not exist

        // Printing the results
        System.out.println("Previous value for Ravi: " + previousValue1); // Should print 25
        System.out.println("Previous value for Vijay: " + previousValue2); // Should print null

        // Printing the updated HashMap
        System.out.println("Updated HashMap: " + people);
    }
}

Output:

Previous value for Ravi: 25
Previous value for Vijay: null
Updated HashMap: {Ravi=25, Priya=30, Vijay=35}

Real-World Use Case: Default Settings Initialization

In a real-world scenario, you might use the putIfAbsent method to initialize default settings for a user if they are not already set.

Example

import java.util.HashMap;

public class DefaultSettingsInitialization {
    public static void main(String[] args) {
        // Creating a HashMap with String keys (setting names) and String values (setting values)
        HashMap<String, String> userSettings = new HashMap<>();

        // Adding some settings to the HashMap
        userSettings.put("theme", "dark");
        userSettings.put("fontSize", "medium");

        // Using putIfAbsent method to set default values
        userSettings.putIfAbsent("theme", "light"); // "theme" already exists
        userSettings.putIfAbsent("language", "English"); // "language" does not exist

        // Printing the updated settings
        System.out.println("User Settings: " + userSettings);
    }
}

Output:

User Settings: {theme=dark, fontSize=medium, language=English}

Conclusion

The HashMap.putIfAbsent(K key, V value) method in Java provides a way to insert a key-value pair into a HashMap only if the specified key is not already associated with a value. By understanding how to use this method, you can efficiently manage default values, avoid overwriting existing data, and ensure that keys are only added when necessary. This method is useful in various scenarios, such as initializing default settings, handling configuration parameters, and managing unique entries in a map.

Comments