Java Hashmap computeIfAbsent() Method
Java Classes
Java is a Object-Oriented programming language. In java everything is based on classes and objects. Basically a class is collection of objects having same properties. Different classes are present in different packages. Hashmap class is a part of java.util package. In hashmap key/value pairs can be stored , but no duplicate key is allowed. Many built-in methods are there in hashmap class. One of those methods is Java Hashmap computeIfAbsent() Method.
To know more about Hashmap computeIfabsent() Method read the complete article.
Java Hashmap computeIfAbsent() Method
The hashmap computeIfAbsent() method is used to assign a new value to the specified key if the key is not present in the hashmap. Below in this page you can find it’s syntax, return values, parameters with detailed examples.
Syntax :
hashmap.computeIfAbsent(Key , Function);
Return Values :
Value :- value which is associated with the key.
Hashmap forEach() Method Example
Example :
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 ("Java", 10); hash_map_1.put ("Hashmap", 20); hash_map_1.put ("computeIfAbsent", 30); hash_map_1.put ("Method", 40); System.out.println ("Original hashmap : " + hash_map_1); int value = hash_map_1.computeIfAbsent ("PrepInsta", k->5 * 10); System.out.println ("Value mapped to key PrepInsta : " + value); //Printing updated hashmap System.out.println ("Updated hashamap : " + hash_map_1); } }
Output :
Original hashmap : {Java=10, Hashmap=20, computeIfAbsent=30, Method=40} Value mapped to key PrepInsta : 50 Updated hashamap : {Java=10, Hashmap=20, computeIfAbsent=30, PrepInsta=50, Method=40}
Now hashmap computeIfAbsent() method is used to check if the specified key is present or not . If the key is not present compute avalue and map it to the specified key.
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