How to Get the Size of HashMap in Java


This case will show us how to get the total number of key-value pairs of a HashMap using the size() method in Java.

Source Code

package com.beginner.examples;

import java.util.HashMap;

public class GetHashMapSizeExample {

	public static void main(String[] args) {
		// Create a HashMap object
		HashMap map = new HashMap();

		// Put key-value
		map.put("a", "97");
		map.put("b", "98");
		map.put("c", "99");
		map.put("d", "100");
		
		//Get the total number using the method size()
		System.out.println("Total number of key-value pairs:" + map.size());
		
		//remove Removes a key-value pair
		map.remove("a");
		
		//After removing
		System.out.println("After removing:"+map.size());

	}

}

Output:

Total number of key-value pairs:4
After removing:3

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments