Why String is popular HashMap key in Java?



import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

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(System.in);

        int phoneNumber = scanner.nextInt();

        for (int i = 0; i < phoneNumber; i++)


                "Enter User Name [key (String)]: ");

            String key = scanner.next();


                "Enter Phone Number [value (Long)]: ");

            long value = scanner.nextLong();




            hashMapOfUsers.put(key.toLowerCase(), value);



            "Get the details of users . . . . . .");

        Iterator hmIterator

            = hashMapOfUsers.entrySet().iterator();



        while (hmIterator.hasNext())

            Map.Entry hashMapElement

                = (Map.Entry)hmIterator.next();





                               + " : "

                               + hashMapElement.getValue());




            "Enter a name to search in the hashmap(key): ");

        String reqKey = scanner.next();





            "Phone number (value): "

            + hashMapOfUsers.get(reqKey.toLowerCase()));


Source link

Leave a Reply

Your email address will not be published.