Get Size or Length of HashMap in Java

In the last tutorial we learnt Sort key and value of HashSet as well as remove all from HashSet .
Now we well learn how to get size from HashMap by use method size() in java to know size or length of collections.

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());
        }
        System.out.println("Hashmap Size :"+set.size());
        set.clear();
        System.out.println("After Remove Hashmap size : "+set.size());
}
//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
Hashmap Size :5
After Remove Hashmap size : 0


EmoticonEmoticon