java.util.HashMap size()

Description :

On this document we will be showing a java example on how to use the size() method. Basically this method just return how many key-value combination in our HashMap. This method might be useful in situation wherein we have to determine the size of our HashMap before performing business operations. Important notes for size method:

  • specified by size in interface Map<K,V>
  • overrides size in class AbstractMap<K,V>

Method Syntax :

public int size()

Parameter Input :

 

DataType Parameter Description
N/A N/A N/A

 

Method Returns :

The size method returns the number of key-value mappings in this map.

Compatibility Version :

Requires Java 1.2 and up

Exception :

N/A

Java Code Example :

This java example source code demonstrates the use of size() method of HashMap class.

package com.javatutorialhq.java.examples;

import java.util.HashMap;
import java.util.Scanner;

/*
 * This example source code demonstrates the use of  
 * size() method of HashMap class
 */

public class HashMapSizeExample {

	public static void main(String[] args) throws InterruptedException {	
		
		// declare the hashmap
		HashMap<String, String> map = new HashMap<>();				
		boolean loopAgain = true;
		Scanner s = new Scanner(System.in);
		
		// loop while user not entering no
		do{
			// ask for user input for id number
			System.out.print("Enter ID number:");			
			String idNumber = s.nextLine();
			
			// ask for user input for Student Name
			System.out.print("Enter your name:");			
			String name = s.nextLine();
			
			// add the user inputs to our hashmap
			map.put(idNumber, name);
			
			// ask user if they want to enter another
			System.out.print("Enter another student (y/n)?");
			String answer = s.nextLine();
			
			// condition to satisfy in order to loop again
			if(answer.equals("y")||answer.equals("Y")){
				continue;				
			}
			else{
				break;
			}
			
		}
		while(loopAgain);
		s.close();
		
		// print the size of the array
		System.out.println("\n**********************************");
		System.out.println("Number of students:"+map.size());
		System.out.println("\n**********************************");
	}

}

Sample Output :

Running the above java example of the usage of HashMap method will give the following output:

HashHamp size method example

HashHamp size method example output

Exception Scenario :

N/A

Similar Method :

  • N/A

Suggested Reading List :

References :