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();
System.out.println("Before Remove HashMap:");
Set set = hMap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry me = (Map.Entry)iterator.next();
System.out.print(me.getKey() + ": ");
System.out.println(me.getValue());
}
set.clear();
System.out.println("After Remove Hashmap :"+set);
}
//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");
return hashMap;
}
}
//result :
Before Remove HashMap:
1: Orange
2: Red Apple
3: Mango
4: Coconut
5: Apple
After Remove Hashmap :[]
EmoticonEmoticon