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

replace()

Example

Substitute the values of entries 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.replace("England", "London");
    capitalCities.replace("Canada", "Ottawa");
    capitalCities.replace("USA", "New York", "Washington DC");
    
    System.out.println(capitalCities);
 }
}

Definition and Usage

The replace() method updates the value of an existing entry in the map. The entry can be identified either by its key or by both its key and value.

Syntax

Choose one of the following:

public V replace(K key, V newValue)
public boolean replace(K key, V oldValue, V newValue)

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

Parameter Values

Parameter

Description

key

Necessary: The key of the entry to be eliminated.

old value

Optional: The value associated with the entry to be removed.

new value

Necessary: The value to be written into the entry.

Technical Details

Returns:

If the oldValue argument is provided, it returns true if the entry was substituted and false otherwise.

If the oldValue argument is omitted, it returns the value the entry had before replacement, or null if there’s no entry with the specified key.