Java – How to get size or length of HashMap ?

In this article, we will discuss how to find size or length of a HashMap or implementation classes of Map interface like LinkedHashMap or TreeMap

1. Map implementation classes:

  • HashMap –> stores entries or Key-Value pairs, in random-order
  • LinkedHashMap –> stores entries or Key-Value pairs, as per insertion-order
  • TreeMap –> stores entries or Key-Value pairs, as per some sorting-order

2. To get size of HashMap :

  • use size() method of Map interface
  • which returns number of Entries or Key-Value pairs in the invoking Map object


int hmSize = hm.size();


import java.util.HashMap;

public class FindSizeOfAHashMap {

	public static void main(String[] args) {

		// creating HashMap object of type <String, String>
		HashMap<String, String> hm = new HashMap<String, String>(); 

		// adding key-value pairs to HashMap object
		hm.put("Google", "Sundar Pichai");
		hm.put("Facebook", "Mark Zuckerberg");
		hm.put("LinkedIn", "Reid Hoffman");
		hm.put("Apple", "Steve Jobs");
		hm.put("Microsoft", "Bill Gates");

		// get size of HashMap
		int hmSize = hm.size();

		// printing size to console
		System.out.println("Size of an HashMap is : " + hmSize);

		// printing all Key-Value pairs
		System.out.println("\n\nall Key-Value pairs:\n\n" + hm);


Size of an HashMap is : 5

all Key-Value pairs:

{LinkedIn=Reid Hoffman, Microsoft=Bill Gates, Apple=Steve Jobs,
Google=Sundar Pichai, Facebook=Mark Zuckerberg}

Related Articles:


Happy Coding !!
Happy Learning !!

Java - Iterate through HashMap in 5 ways
Java - How to get all Entries or Key-Value pairs of HashMap ?