Java HashMap replaceAll() Method

Java HashMap Java HashMap

The replaceAll() method replaces all mappings in the hashMap with the result of executing the given function.

The syntax of the replaceAll() method is:

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

Note:hashmap is an object of the HashMap class.

Parameter Details:

  • function - the function to execute

Return Value

It does not return any value; it only replaces all values in the HashMap.

Example

The following example demonstrates the use of the replaceAll() method:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, String> sites = new HashMap<>();

        // Add some elements to the HashMap
        sites.put(1, "Google");
        sites.put(2, "Example");
        sites.put(3, "Taobao");
        System.out.println("sites HashMap: " + sites);

        // Change all values to uppercase
        sites.replaceAll((key, value) -> value.toUpperCase());
        System.out.println("Updated HashMap: " + sites);
    }
}

Executing the above program produces the following output:

sites HashMap: {1=Google, 2=Example, 3=Taobao}
Updated HashMap: {1=GOOGLE, 2=EXAMPLE, 3=TAOBAO}

(key, value) -> value.toUpperCase()It is an anonymous function lambda expression. It converts all values in the HashMap to uppercase and returns them. To learn more, visitJava Lambda Expressions。

Replace all values with the square of the key:

Example

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // Create a HashMap
        HashMap<Integer, Integer> numbers = new HashMap<>();

        // Add mappings to the HashMap
        numbers.put(5, 0);
        numbers.put(8, 1);
        numbers.put(9, 2);
        System.out.println("HashMap: " + numbers);

        // Replace all values with the square of the key
        numbers.replaceAll((key, value) -> key * key);;
        System.out.println("Updated HashMap: " + numbers);
    }
}

Executing the above program produces the following output:

HashMap: {5=0, 8=1, 9=2}
Updated HashMap: {5=25, 8=64, 9=81}

Java HashMap Java HashMap

Other Extensions