Monday, October 3, 2022

Java Map computeIfPresent() With Examples

The computeIfPresent() method in java.util.Map is added in Java 8 and it computes a new value for the specified key only if value for that key already exists and is not null.

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

computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remappingFunction)

Parameters are as-

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

Method returns the new value associated with the specified key, or null if the computed new value is null. In that case the key, value pair is removed from the map.

Logic for this method is somewhat similar to as given below

if (map.get(key) != null) {
     V oldValue = map.get(key);
     V newValue = remappingFunction.apply(key, oldValue);
     if (newValue != null)
         map.put(key, newValue);
     else
         map.remove(key);
 }
  1. If value for the specified key is null then nothing happens (Map remains as is)
  2. If value for the specified key is not null and the computed new value is also not null then old value is replaced by the new value for the given key.
  3. If value for the specified key is not null and the computed new value is null then the entry for the specified key is removed from the Map.

computeIfPresent () Java examples

1. Here we have a map of items with item and its price as key, value pairs. We'll try to compute a new value for an existing key having a non-null value.

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

public class ComputePresentDemo {

  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);
    // Shoes price increased by 20%
    itemMap.computeIfPresent ("Shoes", (k,v) -> v + (v*20/100));
    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=2400, Trousers=1200}

2. In this example the remappingFunction returns null as the new value. In that case key, value pair should be removed.

public class ComputePresentDemo {

  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);
    // new value as null
    itemMap.computeIfPresent("Shoes", (k,v) -> null);
    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, Trousers=1200}

As you can see entry for key as "Shoes" is removed from our map.

3. If we try to pass a key which doesn't exist (This is for the scenario- If value for the specified key is null) then nothing happens and the HashMap remains unchanged.

In the code key passed to the computeIfPresent() method is not present in the HashMap.

public class ComputePresentDemo {

  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);
    // passing a key that is not in Map
    itemMap.computeIfPresent("Vest", (k,v) -> v + (v * 20/100));
    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}

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


Related Topics

  1. Java Map compute() With Examples
  2. Java Map computeIfAbsent() With Examples
  3. ConcurrentHashMap in Java With Examples
  4. How to Sort Elements in Different Order in TreeSet
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Java Stream - Collectors.groupingBy() With Examples
  2. Lambda Expression Examples in Java
  3. static Block in Java
  4. Fix Scanner.nextLine() Skipping Input After Another next Methods
  5. Java - Could not find or load main class error Fix
  6. How to Read Excel File in Java Using Apache POI
  7. Navigate to a Route Programmatically in Angular
  8. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example

No comments:

Post a Comment