Java Hashmap replaceAll() Method
Java Methods
Methods are used to preform a specific task. Methods are reusable in nature. Instead of writing the code again you can use method to perform that specific task. In Java there are two types of methods, ‘user defined’ and ‘built-in’ methods. User-defined methods are declared by the programmer according to their needs while built-in methods are pre defined methods which make programming easy. The Hashmap class in java also have some inbuilt methods. One of those methods is the Java Hashmap replaceAll() Method.
To know more about Hashmap replaceAll() Method read the complete article
Java Hashmap replaceAll() Method
The hashmap replaceAll() method is used to replace all the mapped values with the result of the given function. No value is returned by this method. Below in this page you can find it’s syntax, return values, parameters with detailed examples.
Syntax :
hashmap.replaceAll(BiFunction<K,V> function);
Return values :
This method does not return any value.
Hashmap replaceAll() Method Examples
Example 1 :
import java.util.*; public class Main { public static void main (String[]args) { // Creating an empty HashMap HashMap < Integer, String > hash_map_1 = new HashMap < Integer, String > (); // Mapping string values to int keys in a empty hashmap hash_map_1.put (10, "Java"); hash_map_1.put (20, "Hashmap"); hash_map_1.put (25, "Values"); hash_map_1.put (30, "Method"); //converting all values to uppercase using replaceAll method hash_map_1.replaceAll ((key, value)->value.toUpperCase (Locale.ROOT)); System.out.println ("updated hashmap values are " + hash_map_1.values ()); } }
Output :
updated hashmap values are [HASHMAP, VALUES, JAVA, METHOD]
Example 2 :
import java.util.*; public class Main { public static void main (String[]args) { // Creating an empty HashMap HashMap < String, Integer > hash_map_1 = new HashMap < String, Integer > (); // Mapping string values to int keys in a empty hashmap hash_map_1.put ("Maths", 80); hash_map_1.put ("English", 75); hash_map_1.put ("Hindi", 85); hash_map_1.put ("Science", 90); System.out.println ("Initial values in hashmap" + hash_map_1.values ()); //increasing all values by 10 using replaceAll method hash_map_1.replaceAll ((key, value)->value = value + 10); System.out.println ("updated hashmap values are : " + hash_map_1.values ()); } }
Output :
Initial values in hashmap[80, 75, 90, 85] updated hashmap values are : [90, 85, 100, 95]
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment