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

merge()

Example

Determine a new value for an entry within a map.

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.merge("Canada", "Ottawa", (a, b) -> a + " -> " + b);
    capitalCities.merge("England", "London", (a, b) -> a + " -> " + b);
    capitalCities.merge("Germany", "Berlin", (a, b) -> a + " -> " + b);
    System.out.println(capitalCities);
 }
}

Definition and Usage

The merge() method either creates a new entry with a specified key and value, or if an entry with the specified key already exists, it calculates a new value for that entry.

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

Syntax

public V merge(K key, V value, BiFunction function)

K and V denote the data types of the keys and values within the map.

Parameter Values

Parameter

Description

key

Required: Specifies the key of the entry.

value

Required: Specifies the value to be used if an entry with the specified key does not exist yet.

function

Required: A BiFunction object or lambda expression that operates on each entry. The function’s first parameter contains the current value of the entry, and the second parameter contains the value specified by the value argument.

Technical Details

Returns:

The value that is stored in the entry.