beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Java – Get size of HashMap example

By Chaitanya Singh | Filed Under: Java Collections

In this example we are gonna see how to get the size of HashMap using size() method of HashMap class. Method definition and description are as follows:

public int size(): Returns the number of key-value mappings in this map.

import java.util.HashMap;

public class SizeExample {
 
 public static void main(String[] args) {
 
    // Creating a HashMap of int keys and String values
    HashMap<Integer, String> hashmap = new HashMap<Integer, String>();
 
    // Adding Key and Value pairs to HashMap
    hashmap.put(11,"Value1");
    hashmap.put(22,"Value2");
    hashmap.put(33,"Value3");
    hashmap.put(44,"Value4");
    hashmap.put(55,"Value5");
 
    // int size() method returns the number of key value pairs 
    System.out.println("Size of HashMap : " + hashmap.size());
 }
}

Output:

Size of HashMap : 5

Since we have 5 key-value pairs in HashMap, the size() method returned integer number 5. Also, in the above example we have taken Integer keys and String values, however if you want to have String key and String value then you can change the generics like this:
HashMap<String, String> hashmap = new HashMap<String, String>();

Remember to add the pairs like this, If you have String keys and values.
hashmap.put("11", "Value1");

Comments

  1. Gayatri says

    April 22, 2015 at 4:48 PM

    Randomly while searching for collection i found this website.Every thing is explained so well n makes it easy to understand and learn.
    If possible do provide test on each topic so that we would me able to test how much we have learnt.
    well thnks as it helped me clearing my concepts.

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

  • Java Tutorial
  • OOPs Concepts

Java Collections

  • ArrayList
  • LinkedList
  • ArrayList vs LinkedList
  • Vector
  • ArrayList vs Vector
  • HashMap
  • TreeMap
  • LinkedHashMap
  • HashSet
  • TreeSet
  • LinkedHashSet
  • Hashtable
  • HashMap vs Hashtable
  • Queue
  • PriorityQueue
  • Deque & ArrayDeque
  • Iterator
  • ListIterator
  • Comparable Interface
  • Comparator Interface
  • Java Collections Interview Q

MORE ...

  • Java String
  • Exception handling
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap