How to Remove a Key Value Pair from HashMap in Java


In this example, we will learn how to remove a key value pair from HashMap object with remove method.

Source Code

package com.beginner.examples;

import java.util.HashMap;

public class RemoveValueHashMap {

	public static void main(String[] args) {

		HashMap map = new HashMap();

		//Put in some key-value pairs
		map.put("a", "97");
		map.put("b", "98");
		map.put("c", "99");
		
		/*Use the remove() method to remove the value of the specified key, 
		 *return null if no value exists, and return the value corresponding to the current key if any
		 */
		Object object = map.remove("a");

		System.out.println(object);
		
		//When removed again, null is returned
		System.out.println(map.remove("a"));

	}

}

Output:

97
null

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments