VOOZH about

URL: https://www.geeksforgeeks.org/java/hashmap-computeifpresentkey-bifunction-method-in-java-with-examples/

⇱ Java HashMap computeIfPresent() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java HashMap computeIfPresent() Method

Last Updated : 12 Jul, 2025

In Java, the computeIfPresent() method of the HashMap class is used to compute a new value for a specified key if the key is already present in the map and its value is not null. If the key is not present, no action is taken.

Example 1: In this example, the computeIfPresent() method updates the value of the key if it exists in the map.


Output
HashMap before operation :
{geeks=3, Geeks=1, for=2}
HashMap after operation :
{geeks=3, Geeks=101, for=2}

Explanation: The above example demonstrates the computeIfPresent() method by updating the value of the key "Geeks" in a HashMap if it exists. The value is incremented by 100, and the updated HashMap is displayed.

Syntax of computeIfPresent() Method

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

Parameters:

  • Key: The key whose presence in the map is to be tested.
  • BiFunction: A function to compute a new value for the given key.

Return Type: The new value associated with the key or null if the key was removed.

Example 2: The below Java program demonstrates that no change will occur in the map if the key is absent.


Output
HashMap before operation :
{geeks=3, Geeks=1, for=2}
HashMap after operation :
{geeks=3, Geeks=1, for=2}


Example 3: If we pass null as the remapping function, a NullPointerException will be thrown.

Output:

👁 Output
Comment