Skip to content
Related Articles
Open in App
Not now

Related Articles

Why String is popular HashMap key in Java?

Improve Article
Save Article
  • Last Updated : 16 Jun, 2022
Improve Article
Save Article

There are many instances when data is stored as key-value pairs. In Java, it can be achieved by “map” which is a collection. Keys usually should not be null and they should point to only one value. In Map, there are various classes available and among them, Hashmap is a class that implements the Map interface.

Hashmap is based on Hashtable. It can allow null values and null keys.

  • The main important thing is that the key should be unique and with that unique key, we can retrieve the values quickly. 
  • First, let us see a sample of storing and displaying the data using Hashmap, and then will see why String is a popular hashmap key in Java!

Let us store a few data of persons containing their mobile numbers:


// HashMap is available in util package
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
// Scanner is needed to get inputs and
// it is also in util package
import java.util.Scanner;
public class StringHashMapExample {
    public static void main(String args[])
        HashMap<String, Long> hashMapOfUsers
            = new HashMap<String, Long>();
            "How many person details containing phone"
            "numbers are going to get stored: ");
        Scanner scanner = new Scanner(;
        int phoneNumber = scanner.nextInt();
        for (int i = 0; i < phoneNumber; i++) {
                "Enter User Name [key (String)]: ");
            String key =;
                "Enter Phone Number [value (Long)]: ");
            long value = scanner.nextLong();
            // Let us store key values as
            // lower case
            hashMapOfUsers.put(key.toLowerCase(), value);
            "Get the details of users . . . . . .");
        Iterator hmIterator
            = hashMapOfUsers.entrySet().iterator();
        // Iterating through Hashmap
        while (hmIterator.hasNext()) {
            Map.Entry hashMapElement
                = (Map.Entry);
            // Printing mark corresponding
            // to string entries
                               + " : "
                               + hashMapElement.getValue());
            "Enter a name to search in the hashmap(key): ");
        String reqKey =;
        // To avoid case mismatch of user names,
        // it is converted to lower case
            "Phone number (value): "
            + hashMapOfUsers.get(reqKey.toLowerCase()));



Why “String” is a popular HashMap Key in java?

1. Hashcode:

  • When we store the data using HashMap, a hash code of the given key is calculated, for example, we have given 2 keys in the above example and for them,  
  • The hashcode is calculated and its value is placed at the position represented by the resultant hash code of the key.
  • Similarly while fetching the data, the hash code is again calculated, by this way the value in the position represented by the hash code is retrieved. Always by checking both hash code equality, the value is retrieved.
  • Other than String, if we use any other datatype and try to change the value and also key, stored hash value (in the storing time) and retrieved hash value (during fetching time) will definitely vary and hence we cannot retrieve the apt value 

2. Immutability:

  • A string is immutable. We cannot modify the value of the string after it got created. This is the main advantage. i.e. hashcode remains the same while storing and also retrieving also. Hence always and also it is a popular approach of using a String variable to hold keys in a hash map.
  • Hashcode is cached and no need to calculate again also (as String immutable)
  • Immutability is a great mechanism to get same hash code every time, for a key object. Hence always it is ideal to go for String and it solves memory leaks, value unavailability, etc.,  
  • hashCode() and equals() methods contract is playing around when data is stored in HashMap. String because of immutability provides maximum support for this.

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!