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

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)/O)

Java Reader/Writer

Java other topics

Java HashMap compute() Usage and Example

Java HashMap Methods

The Java HashMap compute() method calculates a new value and associates it with the specified key in the hash map.

The syntax of the compute() method is:

hashmap.compute(K key, BiFunction remappingFunction)

compute() parameters

The compute() method has two parameters:

  • key - Key associated with the calculated value

  • remappingFunction - For the specifiedKeyFunction to calculate the new value

NoteThe remappingFunction can accept two parameters.

compute() return value

  • Return the new value associated with the key

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

NoteIf the remappingFunction result is null, the specifiedKeymapping.

Example: HashMap compute() to insert a new value

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);
    //With10Percentage discount to recalculate the price of the shoes
    int newPrice = prices.compute("Shoes", (key, value) -> value - value * 10/100);
    System.out.println("Discounted shoe price: ") + newPrice);
    //Print the updated HashMap
    System.out.println("Updated HashMap: ") + prices);
  }
}

Output result

HashMap: {Pant=150, Bag=300, Shoes=200}
Discounted shoe price: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180

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

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

Here,

  • (key, value) -> value - value * 10/100 -  This is a lambda expression. It will reduce the original price of the shoes10% and return. For more information on lambda expressions, please visitJava Lambda Expressions.

  • prices.compute() - Associate the new value returned by the lambda expression with the Shoes mapping.

NoteAccording to the official Java documentation,HashMap merge()The method is simpler than the compute() method.

Recommended Reading

Java HashMap Methods