Java Hashmap remove() Method

hashmap remove method

Methods in Java

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);

Return values :

Value which is mapped to the specified key.
null : If the key is not present in the hashmap.
Java Hashmap remove Method

Hashmap remove() Method Examples

Example 1 :

Run
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

Example 2 :

Run
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

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

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription