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);
ParametersThis method takes two parameters.
key :- Key with which the value is to be mapped.
function :- function that computes the new value for the specified key.
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}
What happened above : In the above example a hashmap is created, initially which is empty and elements are inserted in hash_map_1. 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