bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

Java HashMap replace() Method

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java HashMap replace() Method?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

___ java.util.HashMap;
3Order

Put the learning moves in the order that makes the concept easiest to apply.

The replace() method writes a new value to an existing entry in the map.
Definition and Usage
Java HashMap replace() Method

❮ HashMap Methods

Example

import java.util.HashMap;
public class Main {
  public static void main(String[] args) {
    HashMap<String, String> capitalCities = new HashMap<String, String>();
    capitalCities.put("England", "Cambridge");
    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 writes a new value to an existing entry in the map. The entry can be specified by its key, or by both its key and value.

One of the following

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

K and V refer to the data types of the keys and values of the map.

Parameter Values

ParameterDescription
keyRequired. The key of the entry to be removed.
oldValueOptional. The value of the entry to be removed.
newValueRequired. The value to write into the entry.

Technical Details

Returns:When the oldValue argument is specified, it returns true if the entry was replaced and false otherwise. If the oldValue argument is not specified then it returns the value that the entry had before it was replaced, or null if an entry with the specified key does not exist.

Previous

Java HashMap remove() Method

Next

Java HashMap replaceAll() Method