
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the Size of a HashMap in Java
Use the size() method to get the size of HashMap. Let us first create a HashMap
HashMap hm = new HashMap();
Now, add some elements −
hm.put("Bag", new Integer(1100)); hm.put("Sunglasses", new Integer(2000)); hm.put("Franes", new Integer(800)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600));
Since, we added 5 elements above, therefore, the size() method will give 5 as the result −
set.size()
The following is an example to find the size of HashMap −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("Bag", new Integer(1100)); hm.put("Sunglasses", new Integer(2000)); hm.put("Franes", new Integer(800)); hm.put("Wallet", new Integer(700)); hm.put("Belt", new Integer(600)); Set set = hm.entrySet(); System.out.println("Elements in HashMap..."); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); System.out.println("Size of HashMap = "+set.size()); } }
Output
Elements in HashMap... Franes: 800 Belt: 600 Wallet: 700 Bag: 1100 Sunglasses: 2000 Size of HashMap = 5
Advertisements