10 Examples of HashMap in Java - Programming Tutorial

The HashMap in Java is one of the most popular Collection class among Java programmers. After my article on How HashMap works in Java, which describes theory part of Java HashMap and becomes hugely popular among Java programmers, I thought to share how to use HashMap in Java with some fundamental HashMap examples, but couldn't do that earlier and it was slipped. The HashMap is a data structure, based on hashing, which allows you to store an object as a key-value pair, an advantage of using HashMap is that you can retrieve object on constant time i.e. O(1) if you know the key.

The HashMap class implements Map interface and supports Generics from Java 1.5 release, which makes it type safe. There are a couple of more Collections, which provides similar functionalities like HashMap, which can also be used to store key value pair.

Hashtable is one of them, but Hashtable is synchronized and performs poorly in a single threaded environment. See Hashtable vs HashMap for complete differences between them.

Another one, relatively new is ConcurrentHashMap, which provides better performance than Hashtable in a concurrent environment and should be preferred. See the difference between ConcurrentHashMap and HashMap for detail differences.

In this Java tutorial, we will see different examples of HashMap, like adding and removing entries, iterating over Java HashMap, checking size map, finding if a key or value exists on Map and various other examples, which we used frequently.

Java HashMap Example

Before going to see these examples, few things to note about Java HashMap.It’s not synchronized, so don't share your HashMap among multiple threads. 

Another common cause of the error is clearing Map and reusing it, which is perfectly valid in a single threaded environment but if done in a multi-threaded environment can create subtle bugs.

Java HashMap Example 1: Create and add objects in HashMap

In the first example of HashMap, we will create and add an object to our Map. Always use Generics, if you are not working in Java 1.4. The following code will create HashMap with keys of type String and values of type Integer with default size and load factor.

HashMap<String, Integer> cache = new HashMap<String, Integer>();

alternatively, you can create HashMap from copying data from another Map or Hashtable as shown in below example:
Hashtable<Integer, String> source = new Hashtable<Integer,String>();
HashMap<Integer, String>  map = new HashMap(source);

You can also supply load factor (percentage of size, which if filled trigger resizes of HashMap) and initial capacity while creating an instance by using overloaded constructor provided in API.

Adding elements also called the put operation in HashMap and requires a key and a value object.

Here is an example of adding key and value in Java HashMap:

map.put(21, "Twenty One");
map.put(21.0, "Twenty One"); //this will throw compiler error because 21.0 is not integer

You can further see Java Fundamentals: Collections, a free course from Pluralsight to learn more about HashMap. It's a good course and available for free when you signup for a 10-day free trial.

Java HashMap Example 2: Retrieving value from HashMap

Another basic example is the retrieving value from HashMap. In order to retrieve values, we need to know the key object. let's use the key inserted in the last example, forgetting value back from Map. get(key) method is used to get value from HashMap :

Integer key = 21;
String value = map.get(key);
System.out.println("Key: " + key +" value: "+ value); 

Output: Key: 21 value: Twenty One

See how does get() method internally work in Java to learn more about retrieving mapping in Java. The article explains how get() method uses equals() and hashCode() to retrieve value object even in case of collision.

Java HashMap Example | Java HashMap Tutorial

Java HashMap Example 3: Iterating over HashMap

Another way to get value from HashMap is by iterating over the whole Map. Sometimes we do want to loop through the whole map and perform operations on each key-value pair, we can use Iterator for that purpose.

In order to use Iterator, we first need Set of keys, which can be retrieved using map.keySet() method. By the way, there are multiple ways to loop through Map in Java, see here for 4 ways to loop HashMap in Java.

Here is an example of iterating over Map using java.util.Iterator :

map.put(21, "Twenty One");
map.put(31, "Thirty One");       

Iterator<Integer> keySetIterator = map.keySet().iterator();

  Integer key = keySetIterator.next();
  System.out.println("key: " + key + " value: " + map.get(key));

key: 21 value: Twenty One
key: 31 value: Thirty One

You can also refer Core Java for Impatient by Cay S. Horstmann to learn more about iterating over Map in Java, it also covers new techniques of iteration using forEach() method in Java 8.

10 Example of HashMap in Java

Java HashMap Example 4: Size and Clear in HashMap

Two fundamental examples of HashMap is finding out how many elements are stored in Map, known as the size of Map and clearing HashMap to reuse. Java Collection API provides two convenient methods called size() and clear() to perform these operations on java.util.HashMap, here is code example.

System.out.println("Size of Map: " + map.size());
map.clear(); //clears hashmap , removes all element
System.out.println("Size of Map: " + map.size()); 

Size of Map: 2
Size of Map: 0

You can reuse Map by clearing it, but be careful if it's been shared between multiple threads without proper synchronization. Since you may need to prevent other thread from accessing map when it's getting clear. I suggest not to do until you have a very good reason for doing it.

Java HashMap Example 5 and 6: ContainsKey and ContainsValue Example

In this example of Java HashMap, we will learn how to check if Map contains a particular object as key or value. java.util.HashMap provides convenient methods like containsKey(Object key) and containsValue(Object value) which can be used to for checking the existence of any key value in HashMap.

Here is a code example :

System.out.println("Does HashMap contains 21 as key: " + map.containsKey(21));
System.out.println("Does HashMap contains 21 as value: " + map.containsValue(21));
System.out.println("Does HashMap contains Twenty One as value: " + map.containsValue("Twenty One")); 

Does HashMap contains 21 as key: true
Does HashMap contains 21 as value: false

Does HashMap contains Twenty One as value: true

Java HashMap Example 7: Checking if HashMap is empty

In this Map example, we will learn how to check if HashMap is empty in Java. There are two ways to find out if Map is empty, one is using size() method if size is zero means Map is empty.

Another way to check if HashMap is empty is using more readable isEmpty() method which returns true if Map is empty.

Here is code example :

boolean isEmpty = map.isEmpty();
System.out.println("Is HashMap is empty: " + isEmpty);

Is HashMap is empty: false

Java HashMap Example 8: Removing Objects from HashMap

Another common example of Java HashMap is removing entries or mapping from Map. The java.util.HashMap provides remove(Object key) method, which accepts key and removes mapping for that key.

This method returns null or the value of the entry, just removed. You can also see Java Fundamentals: Collections, a free online Java course from Pluralsight,  to learn more about removing or replacing existing mapping in HashMap.

Anyway, here is a code example of removing key value from HashMap:

Integer key = 21;
Object value = map.remove(key);
System.out.println("Following value is removed from Map: " + value);

Following value is removed from Map: Twenty One

Java HashMap Example 9: Sorting HashMap in Java

HashMap is an unsorted Map in Java, neither key or value is sorted. If you want to sort HashMap than you can sort it based upon key or value, see how to sort HashMap on keys and values for a full code example.

Alternatively, you can use SortedMap in Java like TreeMap. TreeMap has a constructor which accepts Map and can create a Map sorted on the natural order of key or any custom sorting order defined by Comparator.

Only thing is key should be naturally comparable and their compareTo() method shouldn't throw an exception. Just to remind there are no Collections.sort() method defined for Map is only for List and it’s implementation e.g. ArrayList or LinkedList.

So any sorting for Map requires SortedMap or custom code for sorting on either key or value. here is code example of sorting HashMap in Java by using TreeMap in the natural order of keys:

map.put(21, "Twenty One");
map.put(31, "Thirty One");
map.put(41, "Thirty One");

System.out.println("Unsorted HashMap: " + map);
TreeMap sortedHashMap = new TreeMap(map);     
System.out.println("Sorted HashMap: " + sortedHashMap); 

Unsorted HashMap: {21=Twenty One, 41=Thirty One, 31=Thirty One}
Sorted HashMap: {21=Twenty One, 31=Thirty One, 41=Thirty One}

Java HashMap Example 10: Synchronized HashMap in Java

You need to synchronize HashMap if you want to use it in a multi-threaded environment. If you are running on Java 1.5 and above consider using ConcurrentHashMap in place of synchronized HashMap because it provides better concurrency.

If your project is still on JDK 1.4 then you got to use either Hashtable or synchronized Map.

The Collections.synchronizedMap(map) is used to synchronize HashMap in Java. See here for a full code example. This method returns a thread-safe version of Map and all map operation is serialized.

Further Learning
Java Fundamentals: Collections
From Collections to Streams in Java 8 Using Lambda Expressions
Streams, Collectors, and Optional for Data Processing in Java 8
Difference between HashMap and ArrayList in Java
When to use Map, List, and Set collection in Java
Difference between HashMap and HashSet in Java
Difference between IdentityHashMap and HashMap in Java


  1. So far, it is the best intro-article on HashMaps I've ever seen. Please add some practical example of HashMap usage.

  2. Do you know how to get all key value pair from HashMap using core Java library, without any external library? I have a requirement, where I need to convert all HashMap key values to a colon separated String e.g. key : value and send them to another system. I don't know how to convert HashMap to String, as toString() format is not the one I wanted. I have an idea to write a static method, which takes HashMap and returns a String with all key values pair separted by : and individual entries seprated by comma (,) My only problem is I don't know how to get all key values from Map?

    1. Hi Zavier, you can try this :

      HashMap map = new HashMap();//or your hashmap already populated
      for (Entry entry : map.entrySet()) {
      String key = entry.getKey().toString();
      String value = entry.getValue().toString();

      //do what you want with theses strings


  3. Very nice examples, thanks!
    Just one question, if we have the pair (21,"Twenty One") and we want to change it to (21,"Twenty Two") will the
    map.put(21, "Twenty Two"); command work?

    1. Ok, I read in java docs, it will.

  4. Nice tuto mate. Much Help

  5. I never seen this type of tutorial. good tutorial

  6. public class HashMap {

    public static void main(String[] args) {
    java.util.HashMap map = new java.util.HashMap();
    //HashMap map = new HashMap();
    map.put(21, "Twenty One");
    Integer key = 21; String value = map.get(key);
    System.out.println("Key: " + key +" value: "+ value);



    Key: 21 value: Twenty One

  7. Nice one ... very clear and informative!

  8. Thanks... very clear.

  9. Thanks this article helped me a lot

  10. hello,
    I'm doing the java program that connects to the mysql databse.
    there are four different tables in my database and i'm writing the four class respectively.
    the problem is that,
    i want to store my data retrieved from database table into the HashMap collection. and print the data of the Collection.
    Can Anyone tell how can i do this?