java.util.HashMap remove(Object key)

Description :

On this document we will be showing a java example on how to use the remove() method of HashMap Class. Basically this method is to remove key value pair to the HashMap object with the key as the method input. As other methods of HashMap class, Generics should also be considered in using the remove() method. Mean to say that if you declared your HashMap to have an Integer object as the key, then we have to pass Integer object or its subclass as method on the remove method. The use of Generics is to make sure that the object passed is restricted to the object type or its subclass that has been declared on the initialization of our map. If you are interested to learn more about this, please visit the official oracle documentation on Generics.

Important notes for put(K key, V value) method:

  • specified by put in interface Map<K,V>
  • overrides put in class AbstractMap<K,V>

Method Syntax :

public V remove(Object key)

Parameter Input :

 

DataType Parameter Description
Object key key whose mapping is to be removed from the map

 

Method Returns :

The put method returns the previous value associated with key, or null if there was no mapping for key.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Java Code Example :

This java example source code demonstrates the use of remove(Object key) method of HashMap class.  Let’s discuss one by one on the code logic that we have used on the example. First we have declared a HashMap with Integer as key and String as value HashMap<Integer, String> mapStudent = init();

The mapStudent HashMap is equal to the HashMap returned by init() method.  Our purpose in doing this, is to separate the initialization of values of the HashMap since we only want to show how the remove method works. So basically the init method is just there to populate our HashMap with corresponding key value pair. The key is student id while the value will be the Student Name. It’s very clean, isn’t it?

Moving on we have the following statement:

boolean loopAgain = true;
Scanner scan = new Scanner(System.in);

We have the following declaration because, I would like to ask the user multiple times for the student id and remove it accordingly. Here is what I have in mind

do{ 
   //askuserinput for the student id
   // remove the student from hashmap 
   // ask if user if they want another id to enter 
   if Y 
     loop 
   else break 
}while(loopAgain)

The Scanner object is just there to scan the user input. As you can see this is a full pledge java example not only shown how to use the remove method of HashMap class but also we have touch the following:

Below is the full java source code on what we have just discussed which you can readily use for more complicated implementation.

package com.javatutorialhq.java.examples;

import java.util.HashMap;
import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * remove() method of HashMap class
 */

public class HashMapRemoveExample {

	public static void main(String[] args) throws InterruptedException {

		HashMap<Integer, String> mapStudent = init();
		boolean loopAgain = true;
		System.out.println("\nStudent Database Maintenance Menu");
		Scanner scan = new Scanner(System.in);
		// loop until user say no
		do {
			// ask for user input for id number
		
			System.out.print("Enter ID number:");
			Integer idNumber = Integer.parseInt(scan.nextLine());
			// remove the key from our hashmap
			String name =mapStudent.remove(idNumber);
			
			// check if we are able to remove the key
			if(name==null){
				System.out.println("Student id:"+idNumber+" not found");
			}
			else{
				System.out.println("\nRemoving student id:" + idNumber + ","
						+ name);
			}
			
			// ask user input if he wants to remove other			
			System.out.print("\nDo you want to remove another (y/n)? ");
			String answer = scan.nextLine();
			

			if(!(answer.equals("Y")||answer.equals("y"))){
				break;
			}

		} while (loopAgain);
		
		// close the scanner to avoid memory leak
		scan.close();

	}

	public static HashMap<Integer, String> init() {
		// declare the hashmap
		HashMap<Integer, String> mapStudent = new HashMap<>();
		Scanner scan = new Scanner(System.in);

		// populate our hashmap
		mapStudent.put(12487912, "Shyra Travis");
		mapStudent.put(45129987, "Sharon Wallace");
		mapStudent.put(78564568, "Travis Sandler");
		mapStudent.put(46847869, "Rai Salvador");

		// Printing the contents
		System.out.println("\n**********************************");
		System.out.println("The following students are in database");
		System.out.println("   ID Number  " + "      Name");
		for (int id : mapStudent.keySet()) {
			System.out.println("   " + id + "     " + mapStudent.get(id));
		}
		System.out.println("\n**********************************");

		return mapStudent;
	}

}

Sample Output :

Running the above java example of the usage of HashMap remove() method will give the following output:

HashHamp remove example output

HashHamp remove example output

As you would have noticed we have demonstrated on how to handle such cases where the user input is not a valid key. If the returned value of the remove method is found to be null, it means that the key specified as method argument is not on the hashmap object.

Similar Method :

The following are the list of method that you can go through for better understanding of the presented example

  • HashMap put()
  • HashMap keySet()
  • Scanner nextLine()
  • Scanner close()

Suggested Reading List :

The following are the recommended reading materials for further understanding of HashMap

References :