bugl
bugl
HomeLearnPatternsPathsSearchPremium
HomeLearnPatternsPaths

Loading lesson path

Learn/Java/Java Reference
Java•Java Reference

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