English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input/Output (I/O)

Java Reader/Writer

Other Java topics

Usage and examples of Java HashMap computeIfPresent()

Java HashMap Methods

If the key already exists in the hash key, the Java HashMap computeIfPresent() method will calculate a new value and associate it with the specified key.

The syntax of computeIfPresent() method is: }}

hashmap.computeIfPresent(K key, BiFunction remappingFunction)

computeIfPresent() parameters

computeIfPresent() method has two parameters:

  • key - key associated with the calculated value

  • remappingFunction - For the specifiedKeyFunction to calculate the new value

Note:The remappingFunction can accept two parameters.

computeIfPresent() return value

  • Return the new value associated with the specified key

  • If there is no value associated with the key, then return null

Note:If the remappingFunction result is null, the specifiedKeymapping.

Example1:Java HashMap's computeIfPresent()

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    // Creating HashMap
    HashMap<String, Integer> prices = new HashMap<>();
    // Inserting entries into the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: ") + prices);
    //Using10Recompute the value of shoes with the VAT rate
    int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100);
    System.out.println("Price of shoes after adding VAT: ") + shoesPrice);
    // Print the updated HashMap
    System.out.println("Updated HashMap: ") + prices);
  }
}

Output result

HashMap: {Pant=150, Bag=300, Shoes=200}
Price of shoes after adding VAT: 220
Updated HashMap: {Pant=150, Bag=300, Shoes=220}}

In the above example, we created a hash map named prices. Note the expression

prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)

Here,

  • (key, value) -> value + value*10/100  - It is a lambda expression. It calculates the new value of Shoes and returns. For more information about lambda expressions, please visitJava Lambda Expressions.

  • prices.computeIfPresent()  - Associates the new value returned by the lambda expression with the Shoes mapping. This is the only possible because Shoes is already mapped to the value in the hash map.

The computeIfPresent() method cannot be used if the key does not exist in the hash table.

Recommended Reading

Java HashMap Methods