Open In App

Why String is popular HashMap key in Java?

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.



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>();
        System.out.println(
            "How many person details containing phone"
            "numbers are going to get stored: ");
        Scanner scanner = new Scanner(System.in);
        int phoneNumber = scanner.nextInt();
        for (int i = 0; i < phoneNumber; i++) {
            System.out.println(
                "Enter User Name [key (String)]: ");
            String key = scanner.next();
            System.out.println(
                "Enter Phone Number [value (Long)]: ");
            long value = scanner.nextLong();
  
            // Let us store key values as
            // lower case
            hashMapOfUsers.put(key.toLowerCase(), value);
        }
        System.out.println(
            "Get the details of users . . . . . .");
        Iterator hmIterator
            = hashMapOfUsers.entrySet().iterator();
  
        // Iterating through Hashmap
        while (hmIterator.hasNext()) {
            Map.Entry hashMapElement
                = (Map.Entry)hmIterator.next();
  
            // Printing mark corresponding
            // to string entries
            System.out.println(hashMapElement.getKey()
                               + " : "
                               + hashMapElement.getValue());
        }
  
        System.out.println(
            "Enter a name to search in the hashmap(key): ");
        String reqKey = scanner.next();
  
        // To avoid case mismatch of user names,
        // it is converted to lower case
        System.out.println(
            "Phone number (value): "
            + hashMapOfUsers.get(reqKey.toLowerCase()));
    }
}

Output:



 

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

1. Hashcode:

2. Immutability:


Article Tags :