A method is a group of code or set of code which is used perform a certain task. We do not need to write code again and again , instead of writing the code we can use these methods. There are two types of methods in java ‘user defined’ and ‘Inbuilt’ methods. The Hashmap class in java also have some inbuilt methods, one of those method is Java Hashmap remove() Method.
To know more about Hashmap remove() Method read the complete article
Java Hashmap remove() Method
The hashmap remove() method is used to remove the specified key and its mapping value from the hashmap. Below in this page you can find it’s syntax, return values, parameters with detailed examples.
Syntax :
hashmap.remove(Object key);
ParametersThis method takes one parameter. Object key : Key whose mapping is to be remove from the hashmap.
Return values :
Value which is mapped to the specified key. null : If the key is not present in the hashmap.
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, "Remove");
hash_map_1.put (30, "method");
//removing the key using remove() method
String removed=hash_map_1.remove(20);
System.out.println ("Value of removed key is : " + removed);
}
}
Output :
Value of removed key is : Hashmap
What happened above :In the above example a hashmap is created, initially which is empty and elements are inserted in hash_map_1. hash_map_1.remove(20) is called which gives 'Hashmap' as return value beacause Hashmap is mapped to the key 20.
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, "Remove");
hash_map_1.put (30, "method");
//removing the key using remove() method
String removed=hash_map_1.remove(35);
System.out.println ("Value of removed key is : " + removed);
}
}
Output :
Value of removed key is : null
What happened above : In the above example a hashmap is created and key/values pair are inserted . Then hash_map_1.remove(35) is called which gives null as return value because the key 35 is not mapped to any value in tha hash_map_1.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment