Java HashMap replaceAll()

The syntax of the replaceAll() method is:

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

Here, hashmap is an object of the HashMap class.


replaceAll() Parameters

The replaceAll() method takes a single parameter.

  • function - operations to be applied to each entry of the hashmap

replaceAll() Return Value

The replaceAll() method does not return any values. Rather, it replaces all values of the hashmap with new values from function.


Example 1: Change All Values to Uppercase

import java.util.HashMap;

class Main {
    public static void main(String[] args) {
        // create an HashMap
        HashMap<Integer, String> languages = new HashMap<>();

        // add entries to the HashMap
        languages.put(1, "java");
        languages.put(2, "javascript");
        languages.put(3, "python");
        System.out.println("HashMap: " + languages);

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

Output

HashMap: {1=java, 2=javascript, 3=python}
Updated HashMap: {1=JAVA, 2=JAVASCRIPT, 3=PYTHON}

In the above example, we have created a hashmap named languages. Notice the line,

languages.replaceAll((key, value) -> value.toUpperCase());

Here,

  • (key, value) -> value.toUpperCase() is a lambda expression. It converts all values of the hashmap into uppercase and returns it. To learn more, visit Java Lambda Expression.
  • replaceAll() replaces all values of the hashmap with values returned by the lambda expression.

Example 2: Replace all values with the square of keys

import java.util.HashMap;

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

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

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

Output

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

In the above example, we have created a hashmap named numbers. Notice the line,

numbers.replaceAll((key, value) -> key * key);

Here,

  • (key, value) -> key * key - computes the square of key and returns it
  • replaceAll() - replaces all values of the hashmap with values returned by (key, value) -> key * key
Did you find this article helpful?