/*
Remove value from Java HashMap example
This Java Example shows how to remove a key value pair from HashMap object using
remove method.
*/
import java.util.HashMap;
public class RemoveValueFromHashMapExample {
public static void main(String[] args) {
//create HashMap object
HashMap hMap = new HashMap();
//add key value pairs to HashMap
hMap.put("1","One");
hMap.put("2","Two");
hMap.put("3","Three");
/*
To remove a key value pair from HashMap use
Object remove(Object key) method of HashMap class.
It returns either the value mapped with the key or null if no value
was mapped.
*/
Object obj = hMap.remove("2");
System.out.println(obj + " Removed from HashMap");
}
}
/*
Output would be
Two Removed from HashMap
*/
Bookmark/Search this post with:
But is there a way of
But is there a way of deleting a key pair using only the value?
Value!!!
Same question as above: the title is misleading, this doesn't remove a value, this removes a key.
I do not agree
Comment # 1 -> Yes, it is possible to remove key-value using value. Search through the collection and when you find the element delete it using corresponding key.
Comment # 2 ->I do not agree. It deletes the value actually. Collections stores VALUES and associate a key to same for easy retrieval. So actually you are removing value using its key.
Post new comment