Java Utility Library

Java HashMap - replaceAll() Method



The java.util.HashMap.replaceAll() method is used to replace each entry's value in this HashMap with the result of invoking the given function on that entry until all entries have been processed or the function throws an exception.

Syntax

public void replaceAll(BiFunction<? super K,? super V,? extends V> function)

Here, K and V are the type of key and value respectively maintained by the container.


Parameters

function Specify the function to apply to each entry.

Return Value

void type.

Exception

NA.

Example:

In the example below, the java.util.HashMap.replaceAll() method is used to replace each entry's value in the given HashMap by invoking the given function.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a HashMap
    HashMap<Integer, String> MyMap = new HashMap<Integer, String>();

    //populating the HashMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");

    //printing the content of the HashMap
    System.out.println("MyMap contains: " + MyMap);

    //replacing value of key with uppercase value
    MyMap.replaceAll((k, v) -> v.toUpperCase());

    //printing the content of the HashMap
    System.out.println("MyMap contains: " + MyMap); 
  }
}

The output of the above code will be:

MyMap contains: {101=John, 102=Marry, 103=Kim, 104=Jo, 105=Sam}
MyMap contains: {101=JOHN, 102=MARRY, 103=KIM, 104=JO, 105=SAM}

❮ Java.util - HashMap