Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

compute()

Example

Update an entry in a map with a newly computed value.

import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "London");
    capitalCities.put("Germany", "Berlin");
    capitalCities.put("Norway", "Oslo");
    capitalCities.put("USA", "Washington DC");

   
capitalCities.compute("England", (k, v) -> v + "(" + k + ")");
    System.out.println(capitalCities);
  }
}

Definition and Usage

The compute() method updates the value of an existing entry or creates a new entry with a computed value if it doesn’t exist.

The new value is calculated using a function, which can be defined with a lambda expression compatible with Java’s BiFunction interface’s apply() method.

Syntax

public void compute(K key, BiFunction function)

K represents the data type of the map’s keys.

Parameter Values

Parameter

Description

key

Required: Specifies the key for the entry.

function

Required: A BiFunction object or lambda expression that computes the value of the entry.

The function’s first parameter is the entry’s key, and the second parameter is its value.

Technical Details

Returns:

The value calculated by the function.