Java HashMap replaceAll() Method
The replaceAll()
method replaces all mappings in the hashMap with the results of the given function.
The syntax for the replaceAll()
method is:
hashmap.replaceAll(BiFunction<K, V> function)
Note: hashmap
is an object of the HashMap class.
Parameter Description:
function
- The function to be executed.
Return Value
This method does not return any value; it only replaces all values in the HashMap.
Example
The following example demonstrates the use of the replaceAll()
method:
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, "tutorialpro");
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);
}
}
Output:
sites HashMap: {1=Google, 2=tutorialpro, 3=Taobao}
Updated HashMap: {1=GOOGLE, 2=TUTORIALPRO, 3=TAOBAO}
(key, value) -> value.toUpperCase()
is an anonymous function lambda expression. It converts all values in the HashMap to uppercase and returns them. For more information, visit Java Lambda Expressions.
Replace all values with the square of the keys:
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 keys
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}