English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java HashMap replaceAll() method replaces all mappings in the hash table with the result of the specified function.
The syntax of the replaceAll() method is:
hashmap.replaceAll(Bifunction<K, V> function)
function -Operation applied to each entry in the hash map
The replaceAll() method does not return any value. Instead, it replaces all values in the hash map with the new value in the function.
import java.util.HashMap; class Main { public static void main(String[] args) { //Create a HashMap HashMap<Integer, String> languages = new HashMap<>(); //Add an entry to the HashMap languages.put(1, "java"); languages.put(2, "javascript"); languages.put(3, "python"); System.out.println("HashMap: ", + languages); //Change all values to uppercase languages.replaceAll((key, value) -> value.toUpperCase()); System.out.println("Updated HashMap: " + languages); } }
Output Result
HashMap: {1=java, 2=javascript, 3=python} Updated HashMap: {1=JAVA, 2=JAVASCRIPT, 3=PYTHON}
In the above example, we created a hash map named languages. Note this line,
languages.replaceAll((key, value) -> value.toUpperCase());
Here,
(key, value) -> value.toUpperCase() - Is a lambda expression. It converts all values in the hash table to uppercase and returns them. For more information, please visitJava Lambda Expressions.
replaceAll() - Replace all values in the hash map with the value returned by the lambda expression.
import java.util.HashMap; class Main { public static void main(String[] args) { // Create a HashMap HashMap<Integer, Integer> numbers = new HashMap<>(); // Insert entries into 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); } }
Output Result
HashMap: {5=0, 8=1, 9=2} Updated HashMap: {5=25, 8=64, 9=81}
In the above example, we created a hash map named numbers. Note this line,
numbers.replaceAll((key, value) -> key * key);
Here,
(key, value) -> key * key - CalculatekeyReturns the square and
replaceAll() - Using (key, value)->key*Replace the value returned by key with all values of hashmap