Java – HashMap class with examples

In this article, we will discuss HashMap class – one of the Map implemented classes in detail

1. Key points about HashMap:

  • HashMap based on hashcode of keys where
    • keys are unique
    • values can be duplicate

2. HashMap:

  • HashMap is the implementation class of Map interface (i.e.; HashMap implements Map)
  • HashMap uses hashtable to store key-value pairs (which is known as map entry)
  • HashMap allows only unique keys but there is no restriction on values which can be duplicated
  • At any time, HashMap contains only unique keys
  • Insertion-order is NOT maintained
  • While iterating through HashMap, we will get map entries in random-order, as against insertion-order
  • Allows NULL insertion for key but maximum of only one
  • Also, allows NULL insertion for values without any upper limit i.e.; we can insert null value against any unique key
  • Without generics, HashMap allows to insert any type of key and values;
  • With generics, it is type-bounded except, if we take both key-value as Objects within angle brackets
  • HashMap is non-synchronized
  • Search operation is faster i.e.; searching any element from HashMap is faster, as it uses hashing to store elements
  • Present in java.util package and extends java.util.AbstractMap implements java.util.Map interface
  • Also, implements java.lang.Cloneable, marker interfaces which provides special ability to HashMap (provided by JVM at run time) like,
  • java.lang.Cloneable: to create a duplicate object or to clone an object
  • to transfer objects across network

Source: Team BenchResources.Net

3. HashMap constructors:

3.1 HashMap hm = new HashMap();

  • creates an empty HashMap object of size 16
  • with default fill ratio of 0.75

3.2 HashMap hs = new HashMap(int initialCapacity);

  • creates an empty HashMap object of specified size (or initial capacity)
  • with default fill ratio 0.75

3.3 HashMap hs = new HashMap(int initialCapacity, float loadFactor);

  • creates an empty HashMap object of specified size (or initial capacity)
  • and specified fill ratio (for example 0.85)

3.4 HashMap hs = new HashMap(Map m);

  • creates an equivalent HashMap object for specified map
  • it is basically used for inter-conversion between map objects

4. Fill ratio (or Load factor):

  • Fill ratio is also known as Load factor
  • This factor determines when to increase the size of HashMap automatically
  • For example, for the 1st two constructors the default load factor is 0.75 –> which means after filling 75% of original HashMap, new HashMap of bigger size will be created
  • For 3rd constructor, programmer can define load factor while creating HashMap object. If programmer defined it to be 0.95, then after filling 95% of HashMap, size of HashMap will be increased automatically
  • The value of Load factor should be in between 0 to 1.0

5. HashMap examples:


import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HashMapAddAndRemove {

	public static void main(String[] args) {

		// creating HashMap object of type <Integer, String>
		HashMap<Integer, String> hm = new HashMap<Integer, String>();

		// adding key-value pairs to HashMap object
		hm.put(1, "Google");
		hm.put(2, "Facebook");
		hm.put(3, "Yahoo");
		hm.put(4, "Amazon");
		hm.put(5, "Reddit");

		System.out.println("Printing all key-value pairs inside {}\n"
				+ hm + "\n");

		System.out.println("\nIterating using keySet\n");

		// Iterating key-pairs using keySet
		Set<Integer> keys = hm.keySet();
		for(Integer key : keys) {
			System.out.println(key + "  " + hm.get(key));

		System.out.println("\n\nIterating using Map Entry interface\n");

		// Iterating key-pairs using Map entry
		Set set = hm.entrySet();
		Iterator iterator = set.iterator();

		while(iterator.hasNext()) {

			Map.Entry mapEntry = (Map.Entry);
			System.out.println(mapEntry.getKey() + "  "
					+ mapEntry.getValue());

		// removing map entry at 4th position
		System.out.println("\n\nEntry removed at 4th position : "
				+ hm.remove(4));


Printing all key-value pairs inside {}
{1=Google, 3=Yahoo, 2=Facebook, 5=Reddit, 4=Amazon}

Iterating using keySet

1  Google
3  Yahoo
2  Facebook
5  Reddit
4  Amazon

Iterating using Map Entry interface

1  Google
3  Yahoo
2  Facebook
5  Reddit
4  Amazon

Entry removed at 4th position : Amazon

Note: All methods of HashMap is non-synchronized

Q) How to make HashMap synchronized ?

  • HashMap can be easily converted into synchronized HashMap
  • Using utility method synchronizedMap(hm); of java.util.Collections class
Map map = Collections.synchronizedMap(hm);

Related Articles:


Happy Coding !!
Happy Learning !!

Java - LinkedHashMap class with examples
Java - Entry interface