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

 

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

 

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

Syntax:

int hmSize = hm.size();

FindSizeOfAHashMap.java

package in.bench.resources.java.map;

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);
	}
}

Output:

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}

 

References:

 

Happy Coding !!
Happy Learning !!

Various ways to iterate through HashMap - 5 ways
How to get all Entries or Key-Value pairs of HashMap