Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the responsive-lightbox domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114

Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the hueman domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /var/www/wp-includes/functions.php on line 6114
Remove key and value pair from HashMap - Testingpool

Remove key and value pair from HashMap

In the previous post, we have seen how to sort the HashMap on the basis of keys and values. In this post we will see how to remove key and value pair from HashMap.

We use the method named as ‘remove(key)‘ where we need to pass the key which needs to be removed.

Syntax:

public V remove(Object key)

Removes the mapping for the specified key from this map if present.

Example:


import java.util.HashMap;

public class HashMapEx {

	public static void  main(String[] args){
		
		HashMap<Integer,String> hm = new HashMap<Integer,String>();
		hm.put(15, "Mobile");
		hm.put(6, "TV");
		hm.put(10, "Laptop");
		hm.put(2, "Desktop");
		hm.put(1, "Tablet");
		hm.put(23, "Microphone");
		
		System.out.println("HashMap before removing : "+hm);
		Object removeElem1 = hm.remove(6);  //Remove 6 and TV
		Object removeElem2 = hm.remove(2);	//Remove 2 and Desktop
		
		System.out.println("Remove elements are "+removeElem1 +" and "+ removeElem2);
		System.out.println("HashMap after removing : "+hm);
		
	}
}

Output:

HashMap before removing : {1=Tablet, 2=Desktop, 23=Microphone, 6=TV, 10=Laptop, 15=Mobile}
Remove elements are TV and Desktop
HashMap after removing : {1=Tablet, 23=Microphone, 10=Laptop, 15=Mobile}


 

Questions/Suggestions
Have any question or suggestion for us?Please feel free to post in Q&A Forum
Avatar photo

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...