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
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
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 itreplaceAll()- replaces all values of the hashmap with values returned by(key, value) -> key * key