Java – HashMap

HashMap in Java in a collection class which implements Map interface. It is used to store key & value pairs. Each key is mapped to a single value in the map.

Keys are unique. It means we can insert a key ‘K’ only once in a map. Duplicate keys are not allowed. Though a value 'V' can be mapped to multiple keys.

1. java.util.HashMap Class

1.1. HashMap class declaration

HashMap has been declared as following:

public class HashMap<K,V> extends AbstractMap<K,V> 
				implements Map<K,V>, Cloneable, Serializable  

1.2. HashMap class Hierarchy

As shown above, HashMap implements Map interface and extends AbstractMap class.

HashMap Hierarchy
HashMap Hierarchy

2. Java HashMap Features

  • HashMap cannot contain duplicate keys.
  • HashMap allows multiple null values but only one null key.
  • HashMap is an unordered collection. It does not guarantee any specific order of the elements.
  • HashMap is not thread-safe. You must explicitly synchronize concurrent modifications to the HashMap. Or you can use Collections.synchronizedMap(hashMap) to get the synchronized version of HashMap.
  • A value can be retrieved only using the associated key.
  • HashMap stores only object references. So primitives must be used with their corresponding wrapper classes. Such as int
  • will be stored as Integer.
  • HashMap implements Cloneable and Serializable interfaces.

3. HashMap internal implementation

HashMap works on principle of hashing. Hashing is a way to assigning a unique code for any variable/object after applying any formula/algorithm on its properties. Each object in java has it’s hash code in such a way that two equal objects must produce the same hash code consistently.

3.1. HashMap.Entry class

The key-value pairs are stored as instance of inner class HashMap.Entry which has key and value mapping stored as attributes. key has been marked as final.

static class Entry<K ,V> implements Map.Entry<K, V>
{
    final K key;
    V value;

    Entry<K ,V> next;
    final int hash;

    ...//More code goes here
}

3.2. Internal working

All instances of Entry class are stored in an array declard as 'transient Entry[] table'. For each key-value to be stored in HashMap, a hash value is calculated using the key’s hash code. This hash value is used to calculate the index in the array for storing Entry object.

In case of collision, where multiple keys are mapped to single index location, a linked list of formed to store all such key-value pairs which should go in single array index location.

While retrieving the value by key, first index location is found using key’s hashcode. Then all elements are iterated in the linkedlist and correct value object is found by identifying the correct key using it’s equals() method.

4. Java HashMap Example

Let’s quickly go through some examples to work with HashMap in Java.

4.1. Add key-value – HashMap.put()

import java.util.HashMap;

public class HashMapExample 
{
    public static void main(String[] args) throws CloneNotSupportedException 
    {
        HashMap<Integer, String> map = new HashMap<>();
        
        map.put(1,  "A");
        map.put(2,  "B");
        map.put(3,  "C");
        
        System.out.println(map);
    }
}

Program output.

{1=A, 2=B, 3=C}

4.2. Get value by key – HashMap.get()

HashMap<Integer, String> map = new HashMap<>();
        
map.put(1,  "A");
map.put(2,  "B");
map.put(3,  "C");

String value = map.get(2);

System.out.println("The value is :: "+  value );

Program output.

The value is :: B

4.3. Remove pair by key – HashMap.remove()

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

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

System.out.println(map);

map.remove(3);

System.out.println(map);

Program output.

{1=A, 2=B, 3=C}
{1=A, 2=B}

4.4. Iterate a HashMap

Please note that iterators of this class are fail-fast and if any structure modification is done after creation of iterator, it will throw ConcurrentModificationException.

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

map.put(1, "A");
map.put(2, "B");
map.put(3, "C");

System.out.println("//Iterate over keys");

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

while (itr.hasNext()) 
{
    Integer key = itr.next();
    String value = map.get(key);
    
    System.out.println("The key is :: " + key + ", and value is :: " + value );
}

System.out.println("//Iterate over entries set");

Iterator<Entry<Integer, String>> entryIterator = map.entrySet().iterator();

while (entryIterator.hasNext()) 
{
    Entry<Integer, String> entry = entryIterator.next();
    
    System.out.println("The key is :: " + entry.getKey() + ", and value is :: " + entry.getValue() );
}

Program output.

//Iterate over keys
The key is :: 1, and value is :: A
The key is :: 2, and value is :: B
The key is :: 3, and value is :: C

//Iterate over entries set
The key is :: 1, and value is :: A
The key is :: 2, and value is :: B
The key is :: 3, and value is :: C

5. HashMap Methods

List of methods in HashMap class and their short description.

  1. void clear() : removes all the key-value pairs from the HashMap.
  2. Object clone() : returns a shallow copy of the specified HashMap.
  3. boolean containsKey(Object key) : returns true or false based on whether the specified key is found in the map or not.
  4. boolean containsValue(Object Value) : Similar to containsKey() method, it looks for the specified value instead of key.
  5. Object get(Object key) : returns the value for the specified key in the HashMap.
  6. boolean isEmpty() : checks whether the map is empty.
  7. Set keySet() : returns the Set of the all keys stored in the HashMap.
  8. Object put(Key k, Value v) : Inserts key-value pair into the HashMap.
  9. int size() : returns the size of the map which is equal to the number of key-value pairs stored in the HashMap.
  10. Collection values() : returns a collection of all values in the map.
  11. Value remove(Object key) : removes the key-value pair for the specified key.
  12. void putAll(Map m) : copies all the elements of a map to the another specified map.

6. HashMap tutorials and examples

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.