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

computeIfPresent()

Example

Compute a new value for an existing entry in a map if the entry’s key is present and its current value is not null.

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.computeIfPresent("England", (k, v) -> v + "(" + k + ")");
    System.out.println(capitalCities);
  }
}

Definition and Usage

The computeIfPresent() method computes a value for an entry based on its key. If an entry with the specified key does not exist or its value is null, the map remains unchanged.

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

Syntax

public void computeIfPresent(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 Function object or lambda expression that computes the value of the entry.

The function’s first parameter holds the entry’s key, while the second parameter holds its value.

Technical Details

Returns:

The computed value by the function or null if there is no change in the map.