Tuesday, October 4, 2022

Java Map computeIfAbsent() With Examples

The computeIfAbsent() method in java.util.Map is added in Java 8 and it computes a new value for the specified key only if that key is not already present in the Map or it is present but associated with a null value.

Syntax of the computeIfAbsent() method is as given below.

computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction)

Parameters are as-

  • key- First parameter is the key with which the value is to be associated.
  • remappingFunction- This parameter is of type Function functional interface and provides a function to compute a value.

Method returns the new value associated with the specified key if the old value was null otherwise return the old value itself. Returns null in case computed new value is null.

Logic for this method is somewhat similar to as given below.

if (map.get(key) == null) {
     V newValue = mappingFunction.apply(key);
     if (newValue != null)
         map.put(key, newValue);
 }
  1. If value for the specified key is null and the computed new value is not null then add this entry to the Map.
  2. If value for the specified key is null and the computed new value is also null then do nothing (Map remains unchanged).
  3. If old value for the specified key is not null (key already present) then also Map remains unchanged.

computeIfAbsent() Java examples

1. Here we have a map of items with item and its price as key, value pairs. We'll try to add a new entry to the Map by checking if that key is already not present.

import java.util.HashMap;
import java.util.Map;

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // adding new entry
    itemMap.computeIfAbsent("Belt", (k) -> 750);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Belt=750, Shirt=800, Shoes=2000, Trousers=1200}

As you can see a new key, value pair Belt=750 is added to the HashMap.

2. If key is already there but the value is null then value is modified if new value is not null.

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", null);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
    // modify value for key with null value
    itemMap.computeIfAbsent("Belt", (k) -> 750);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=null, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}

3. If non-null value is already present for the specified key then the map remains unchanged.

public class ComputeAbsentDemo {

  public static void main(String[] args) {
    Map<String, Integer> itemMap = new HashMap<>();
    itemMap.put("Trousers", 1200);
    itemMap.put("Shirt", 800);
    itemMap.put("Shoes", 2000);
    itemMap.put("Belt", 750);
    
    System.out.println("*** Map Initially ***");
    System.out.println(itemMap);
      
    itemMap.computeIfAbsent("Belt", (k) -> 850);
    System.out.println("*** Map After compute ***");
    System.out.println(itemMap);
  }
}

Output

*** Map Initially ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}
*** Map After compute ***
{Shirt=800, Belt=750, Shoes=2000, Trousers=1200}

Since key "Belt" is already there in the HashMap with an associated non-null value, Map remains unchanged (Value for key "Belt" doesn't change to 850).

That's all for this topic Java Map computeIfAbsent() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Java Map computeIfPresent() With Examples
  2. Java Map putIfAbsent() With Examples
  3. ConcurrentSkipListMap in Java With Examples
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Java DelayQueue With Examples

You may also like-

  1. Generics in Java
  2. How HashSet Works Internally in Java
  3. Why Java String is Immutable
  4. BigInteger in Java With Examples
  5. Java Program to Delete a Node From Binary Search Tree (BST)
  6. Pure and Impure Pipes in Angular
  7. Spring Email Scheduling Example Using Quartz Scheduler
  8. Spring JdbcTemplate Insert, Update And Delete Example

No comments:

Post a Comment