Java LinkedHashMap computeIfAbsent() Method

The LinkedHashMap.computeIfAbsent() method in Java is used to compute a value for a specific key if the key is not already associated with a value (or is mapped to null).

Table of Contents

  1. Introduction
  2. computeIfAbsent Method Syntax
  3. Examples
    • Computing Values for Absent Keys
    • Handling Existing Keys
  4. Real-World Use Case
    • Example: Initializing Default Values
  5. Conclusion

Introduction

The LinkedHashMap.computeIfAbsent() method is a member of the LinkedHashMap class in Java. It allows you to compute a value for a specific key if the key is not already associated with a value (or is mapped to null). This method is useful for initializing default values or performing computations only when necessary.

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.
    • 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

Computing Values for Absent Keys

The computeIfAbsent method can be used to compute and insert values for keys that are not already present in the LinkedHashMap.

Example

import java.util.LinkedHashMap;
import java.util.function.Function;

public class ComputeIfAbsentExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap with String keys and Integer values
        LinkedHashMap<String, Integer> people = new LinkedHashMap<>();

        // Adding some entries to the LinkedHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);

        // Computing a value for a key that is absent
        Integer ageVijay = people.computeIfAbsent("Vijay", new Function<String, Integer>() {
            @Override
            public Integer apply(String key) {
                return 35;
            }
        });

        // Printing the result and the LinkedHashMap after computation
        System.out.println("Computed age for Vijay: " + ageVijay);
        System.out.println("LinkedHashMap after computation: " + people);
    }
}

Output:

Computed age for Vijay: 35
LinkedHashMap after computation: {Ravi=25, Priya=30, Vijay=35}

Using Lambda Expression with computeIfAbsent

You can also use a lambda expression to simplify the code.

Example

import java.util.LinkedHashMap;

public class ComputeIfAbsentLambdaExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap with String keys and Integer values
        LinkedHashMap<String, Integer> people = new LinkedHashMap<>();

        // Adding some entries to the LinkedHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);

        // Computing a value for a key that is absent using a lambda expression
        Integer ageVijay = people.computeIfAbsent("Vijay", key -> 35);

        // Printing the result and the LinkedHashMap after computation
        System.out.println("Computed age for Vijay: " + ageVijay);
        System.out.println("LinkedHashMap after computation: " + people);
    }
}

Output:

Computed age for Vijay: 35
LinkedHashMap after computation: {Ravi=25, Priya=30, Vijay=35}

Handling Existing Keys

The computeIfAbsent method does not modify the value if the key already has an associated value.

Example

import java.util.LinkedHashMap;

public class ExistingKeyExample {
    public static void main(String[] args) {
        // Creating a LinkedHashMap with String keys and Integer values
        LinkedHashMap<String, Integer> people = new LinkedHashMap<>();

        // Adding some entries to the LinkedHashMap
        people.put("Ravi", 25);
        people.put("Priya", 30);

        // Attempting to compute a value for an existing key
        Integer agePriya = people.computeIfAbsent("Priya", key -> 35);

        // Printing the result and the LinkedHashMap after computation
        System.out.println("Computed age for Priya: " + agePriya);
        System.out.println("LinkedHashMap after computation: " + people);
    }
}

Output:

Computed age for Priya: 30
LinkedHashMap after computation: {Ravi=25, Priya=30}

Real-World Use Case

Example: Initializing Default Values

A common real-world use case for LinkedHashMap.computeIfAbsent() is initializing default values when they are not present in the map. For example, let’s consider a scenario where user preferences are stored, and we need to initialize default preferences for users who do not have any preferences set.

Example

import java.util.LinkedHashMap;

public class InitializeDefaultValues {
    public static void main(String[] args) {
        // Creating a LinkedHashMap to store user preferences
        LinkedHashMap<String, String> userPreferences = new LinkedHashMap<>();

        // Adding some user preferences to the LinkedHashMap
        userPreferences.put("Ravi", "Dark Theme");
        userPreferences.put("Priya", "Light Theme");

        // Initializing default preferences for users who do not have preferences set
        String vijayPreference = userPreferences.computeIfAbsent("Vijay", key -> "Dark Theme");

        // Printing the result and the LinkedHashMap after computation
        System.out.println("Preference for Vijay: " + vijayPreference);
        System.out.println("User Preferences after computation: " + userPreferences);
    }
}

Output:

Preference for Vijay: Dark Theme
User Preferences after computation: {Ravi=Dark Theme, Priya=Light Theme, Vijay=Dark Theme}

In this example, LinkedHashMap.computeIfAbsent() is used to initialize default preferences for users who do not have any preferences set, demonstrating how to handle absent values effectively.

Conclusion

The LinkedHashMap.computeIfAbsent() method in Java provides a way to compute a value for a specific key 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 and initialize values in your Java applications, making it a versatile tool for data management.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top