What is the replaceAll function in Java HashMap?

The replaceAll function in Java comes with the HashMap class and is used to apply a function on all the key-value pairs present inside a HashMap object. When applied to a key-value pair, the result of the prescribed function replaces the information stored in the value field of the corresponding pair.

Syntax

The following syntax is used to call the replaceAll function.

hashmap.replaceAll(Bifunction<K, V> function)

In the snippet above, hashmap is a HashMap object.

Parameters

The replaceAll function takes in only one argument:

  • function: the function to be applied on each key-value pair in the HashMap object.

Return value

The return type is void, so the replaceAll function does not return anything. However, upon successful execution, it replaces the value of all key-value pairs in the HashMap object with the return value of the function prescribed in the arguments to replaceAll.

An exception is thrown in case an error occurs.

Example

The program below demonstrates how to use the replaceAll function. We declare a HashMap object named countries, which stores the rank and name of the four largest countries (area wise) as key-value pairs. Each country name is in lower case.

We apply the toUpperCase function using the replaceAll method on each key-value pair. All characters in the value field are transformed into upper case.

To observe the difference in the value of field of each key-value pair, we print the state of the countries before and after applying the replaceAll function.

import java.util.HashMap;
class Main {
public static void main(String[] args) {
System.out.println("This program ranks countries on the basis of land-area covered.");
System.out.println("Each key in the HashMap is a rank and each corresponding value is a country name.");
// create an HashMap
HashMap<Integer, String> countries = new HashMap<>();
// populate the HashMap
countries.put(1, "russia");
countries.put(2, "canada");
countries.put(3, "china");
countries.put(4, "united states");
System.out.println("**Printing original HashMap**");
System.out.println(countries);
// Apply replaceAll
countries.replaceAll((rank, country) -> country.toUpperCase());
System.out.println("**Printing HashMap after applying replaceAll**");
System.out.println( countries);
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved