Java Hashmap Replaceall
# Java HashMap replaceAll() Method
[ Java HashMap](#)
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 function)
**Note:** hashmap is an object of the HashMap class.
**Parameter Description:**
* function - The function to execute
### Return Value
Does not return any value, 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 sites = new HashMap();
// Add some elements to the HashMap
sites.put(1, "Google");
sites.put(2, "");
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);
}
}
The output of the above program is:
sites HashMap: {1=Google, 2=, 3=Taobao}
Updated HashMap: {1=GOOGLE, 2=, 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 (#).
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 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);
}
}
The output of the above program is:
HashMap: {5=0, 8=1, 9=2}
Updated HashMap: {5=25, 8=64, 9=81}
[ Java HashMap](#)
YouTip