![]() |
VOOZH | about |
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.
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.
default V computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)
Parameters:
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.
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: