Java Utility Library

Java WeakHashMap - replaceAll() Method



The java.util.WeakHashMap.replaceAll() method is used to replace each entry's value in this map 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.WeakHashMap.replaceAll() method is used to replace each entry's value in the given WeakHashMap by invoking the given function.

import java.util.*;

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

    //populating the map
    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 map
    System.out.println("MyMap contains: " + MyMap);

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

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

The output of the above code will be:

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

❮ Java.util - WeakHashMap