HashMap is one of the most important Map implementation classes in Java Collections Framework. Let’s understand in detail.

What is a Map?

  • A map is an object that has key/value associations. The map provides a way to store key/value pairs.
  • While both keys and values are objects, keys must be unique whereas values need not be unique.
  • Keys are used to identifying and retrieving values from a map.

Java enables functionality to work with maps through the Map interface. And the get(), put()methods in Map interface are used to retrieve and store values into a map respectively.

The HashMap Class

HashMap is a generic class that implements the Map interface and has the following declaration:

class HashMap<K, V>

In the above declaration, K indicates the type of keys and V indicates the type of values in the map.

Example:

HashMap<String, Float> hm = new HashMap<String, Float>();

A HashMap instance has two parameters, namely, initial capacity and load factor.

  • Initial Capacity: is the capacity of the HashMap instance at the time of creation. It denotes the number of buckets assigned to the hash table for data storage.
  • Load Factor: specifies the maximum limit of the hash map at which the current capacity of the hash table needs to be increased.

Default Initial Capacity and Load Factor :

The default initial capacity and a load factor of HashMap instances are 16 and 0.75 respectively. While creating a HashMap instance, you can either specify values for the initial capacity and load factor or allow Java to use the default values.

Rehashing :

The automatic mechanism that increases the capacity of a hash map is called rehashing. The initial capacity and load factors are important because too many rehash operations affect the performance of the hash map. Therefore, care must be taken to set the optimal initial capacity and load factor.

Note: The HashMap class provides constant-time performance for the get and put operations. If it’s granted that the hash function stores the elements evenly across buckets, the time complexity of the operations in a HashMap instance is O(1).

Key points :

  1. HashMap is fast.
  2. HashMap stores key along with the value pairs.
  3. HashMap allows only one null key, whereas we can insert any number of null values.
  4. HashMap works on the principle of hashing.
  5. HashMap is not a thread-safe class, that means the methods in a hashmap are not synchronized.
  6. HashMap doesn’t maintain the insertion order. This is almost similar like HashTable class apart from the thread safing.
  7. The default initial capacity of HashMap is 16, and the default load factor of a HashMap is 0.75

Constructors in HashMap class:

Constructor Description
HashMap() A default hash map with 16 as the initial capacity and 0.75 as the load factor.
HashMap(Map map) A hash map with the mappings specified by Map and initializes it using the elements of m.
HashMap(int initialCapacity) A hash map with the initial capacity specified by the initialCapacity parameter and 0.75 load factor.
HashMap(int initialCapacity, float loadFactor) A hash map with the initial capacity specified by the initialCapacity parameter and the load factor specified by the loadFactor parameter.

Example

The following program is an example that uses a HashMap instance to store customer names and account balance information.

HashMapExample.java
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
 
public class HashMapExample {
 
    public static void main(String args[]) {
        HashMap<string, double=""> hm = new HashMap<string, double="">();
 
        hm.put("Jason Smith", new Double(2325.34));
        hm.put("Joey Williams", new Double(553.52));
        hm.put("Angelina Johnson", new Double(658.25));
        hm.put("Tedd Wilson", new Double(100.50));
        hm.put("Katherine Hunt", new Double(-18.28));
 
        Set<map.entry<string, double="">> set = hm.entrySet();
        for (Map.Entry<string, double=""> me : set) {
            System.out.print(me.getKey() + ": ");
            System.out.println(me.getValue());
        }
        System.out.println();
 
        double balance = hm.get("Angelina Johnson");
        hm.put("Angelina Johnson", balance + 500);
        System.out.println("Angelina Johnson's new balance: "
                + hm.get("Angelina Johnson"));
    }
}</string,></map.entry<string,></string,></string,>

Output  :

Terminal
Jason Smith: 2325.34
Angelina Johnson: 658.25
Tedd Wilson: 100.5
Katherine Hunt: -18.28
Joey Williams: 553.52 Angelina Johnson's new balance: 1158.25

In the above example, hm is a HashMap instance that stores customer name and account balance as a key/value pair of string and double values. By using the put() method, the keys and values are stored into the hash map.

The entrySet()method is used to obtain a set-view of the hash map. The result of this method is a set of elements that contain the HashMap entries. Here entry represents the key and value.

Each element in this set is an object of the Map.Entry interface. The program uses a for each loop with the getKey() and getValues() methods to display all the map entries and then updates the value in Angelina Johnson’s account.

Happy Learning 🙂