Remove Mapping From HashMap

In this section we will learn how to remove element from HashMap in Java .


See Example: 

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

public class Example2 {

public static void main(String[] args) {
HashMap<Integer, String> hMap = getHashMapKeyAndValue();
}
//Declare method 
public static  HashMap<Integer, String> getHashMapKeyAndValue(){
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(1, "Orange");
hashMap.put(5, "Apple");
hashMap.put(3, "Mango");
hashMap.put(4, "Coconut");
hashMap.put(2, "Red Apple");
for(Map.Entry  map : hashMap.entrySet()){
System.out.println("Key :"+ map.getKey() + " & Value : " +map.getValue());
}
//remove  key&value pairs for key 2
Object removeObj = hashMap.remove(2);
System.out.println("HashMap Elements remove key = " + removeObj);
 
System.out.println("After remove element " );
for(Map.Entry  map : hashMap.entrySet()){
System.out.println("Key :"+ map.getKey() + " & Value : " +map.getValue());
}
return hashMap;
}
}
//result:

Key :1 & Value : Orange
Key :2 & Value : Red Apple
Key :3 & Value : Mango
Key :4 & Value : Coconut
Key :5 & Value : Apple
HashMap Elements remove key = Red Apple
After remove element 
Key :1 & Value : Orange
Key :3 & Value : Mango
Key :4 & Value : Coconut
Key :5 & Value : Apple


EmoticonEmoticon