Get size of HashMap in Java

In this tutorial, we will learn how to Get size of HashMap in Java.

HashMap in Java is a hash table based implementation of Map Interface. It is used to store key-value pairs. HashMap is a widely used collection classes in java.  HashMap class is similar to Hashtable, except that it is not synchronized and it allows null key and values. HashMap in Java is an unordered collection which means that this class does not guarantee that the order will remain constant over the time. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

In we want to calculate the size or no. of elements in HashMap, then this class in Java provides size() method to get size of HashMap. The size method returns the size or the no. of elements in HashMap. The syntax of size() method is:

Syntax of size() method:

Returns:
the number of elements in this map

Example:

Output:

 

Related posts

Leave a Comment