HashMap computeIfPresent() method in java

Let’s learn HashMap computeIfPresent() method in java.

HashMap computeIfPresent(K key, BiFunction <? super K, ? super V,? extends V> remappingFunction) method in java

computeIfPresent(K key, BiFunction <? super K, ? super V,? extends V> remappingFunction) method returns the new value associated with the specified key, or null if none.

If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.

If the remapping function returns null, the mapping is removed. If the remapping function itself throws an (unchecked) exception, the exception is rethrown, and the current mapping is left unchanged.

This method will throw a ConcurrentModificationException if it is detected that the remapping function modifies this map during computation.

Syntax

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

Parameters

key key with which the specified value is to be associated
remappingFunction the remapping function to compute a value

Throws

ConcurrentModificationException – if it is detected that the remapping function modified this map

Example

import java.util.*;

class HashMapComputeIfPresentDemo 
{
   public static void main(String[] args) 
   {
      HashMap<String, Integer> hm = new HashMap<>();
      hm.put("Apples", 2);
      hm.put("are", 4);
      hm.put("apples", 6);
      System.out.println("Hashmap before computeIfPresent : " + hm);
      // add new value for keys which is present using computeIfPresent method
      hm.computeIfPresent("Apple", (key, val) -> val + 100);
      System.out.println("HashMap after computeIfPresent : " + hm);

   }
}

Output:

Hashmap before computeIfPresent : {Apples=2, are=4, apples=6}
HashMap after computeIfPresent : {Apples=2, are=4, apples=6}


import java.util.*;

class HashMapComputeIfPresentDemo 
{
   public static void main(String[] args) 
   {
      HashMap<String, Integer> hm = new HashMap<>();
      hm.put("Apples", 2);
      hm.put("are", 4);
      hm.put("apples", 6);
      System.out.println("Hashmap before computeIfPresent : " + hm);
      // add new value for keys which is present using computeIfPresent method
      hm.computeIfPresent("are", (key, val) -> val + 1);
      System.out.println("HashMap after computeIfPresent : " + hm);
   }
}

Output:

Hashmap before computeIfPresent : {Apples=2, are=4, apples=6}
HashMap after computeIfPresent : {Apples=2, are=5, apples=6}


Also read – inheritance in java