Write a Java program to get the size of the HashMap collection


This Java program creates a HashMap named stu with keys of type Integer and values of type String. It then adds ten key-value pairs to the map using the put() method.

key-value pairs to the map using the put() method. The program then uses the size() method to determine the number of key-value pairs in the HashMap and prints the result using System.out.println().

Finally, the program prints the message "Size of HashMap : " followed by the number of elements in the HashMap.

Source Code

import java.util.*;
public class GetSize
{
	public static void main(String[] args)
	{
		HashMap < Integer, String > stu = new HashMap < > ();
		stu.put(101, "Kim");
		stu.put(102, "Arun");
		stu.put(103, "Deepika");
		stu.put(104, "Ramesh");
		stu.put(105, "Joes");
		stu.put(106, "Abi");
		stu.put(107, "John");
		stu.put(108, "Vijay");
		stu.put(109, "Suga");
		stu.put(110, "Siva");
 
		System.out.println("Size of HashMap : " + stu.size());
	}
}

Output

Size of HashMap : 10