Write a Java program to count the number of key-value (size) mappings in a map


This is a Java program that demonstrates how to count the number of key-value pairs in a HashMap. Here's how it works:

  • First, a HashMap object is created using the HashMap class. This specifies that the keys in the HashMap will be of type Integer, while the values will be of type String.
  • Next, key-value pairs are added to the HashMap using the put() method. In this example, we add five pairs, with keys ranging from 1 to 5, and string values representing different types of fruits.
  • Finally, the size() method is used to get the number of key-value pairs in the HashMap, which is then printed to the console.

Source Code

import java.util.*;  
public class CountNum_KeyValue
{  
	public static void main(String args[])
	{  
		HashMap<Integer,String> hash_map = new HashMap<Integer,String>();  
		hash_map.put(1, "Cherry");
		hash_map.put(2, "Banana");
		hash_map.put(3, "Apple");
		hash_map.put(4, "Mango");
		hash_map.put(5, "Guava");
		System.out.println("Count Number of Key-Value in HashMap : "+hash_map.size());
	}
}

Output

Count Number of Key-Value in HashMap : 5