In this example we are gonna see how to get the size of HashMap using size() method of HashMap class. Method definition and description are as follows:
public int size()
: Returns the number of key-value mappings in this map.
import java.util.HashMap; public class SizeExample { public static void main(String[] args) { // Creating a HashMap of int keys and String values HashMap<Integer, String> hashmap = new HashMap<Integer, String>(); // Adding Key and Value pairs to HashMap hashmap.put(11,"Value1"); hashmap.put(22,"Value2"); hashmap.put(33,"Value3"); hashmap.put(44,"Value4"); hashmap.put(55,"Value5"); // int size() method returns the number of key value pairs System.out.println("Size of HashMap : " + hashmap.size()); } }
Output:
Size of HashMap : 5
Since we have 5 key-value pairs in HashMap, the size() method returned integer number 5. Also, in the above example we have taken Integer keys and String values, however if you want to have String key and String value then you can change the generics like this:
HashMap<String, String> hashmap = new HashMap<String, String>();
Remember to add the pairs like this, If you have String keys and values.
hashmap.put("11", "Value1");
Gayatri says
Randomly while searching for collection i found this website.Every thing is explained so well n makes it easy to understand and learn.
If possible do provide test on each topic so that we would me able to test how much we have learnt.
well thnks as it helped me clearing my concepts.