Java HashMap computeIfAbsent() Method

The 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

  1. Introduction
  2. computeIfAbsent Method Syntax
  3. Examples
    • Adding an Entry If Absent in a HashMap
    • Real-World Use Case: Initializing Default Configurations
  4. 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:
    • key of type K, which represents the key whose value is to be computed and inserted if absent.
    • mappingFunction of type Function<? 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 null if the computed value is null.

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.

Comments