Why String is popular HashMap key in Java?

by:

Softwares


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>();

        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();

  

            

            

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

        

        System.out.println(

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

        Iterator hmIterator

            = hashMapOfUsers.entrySet().iterator();

  

        

        while (hmIterator.hasNext())

            Map.Entry hashMapElement

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

  

            

            

            System.out.println(hashMapElement.getKey()

                               + " : "

                               + hashMapElement.getValue());

        

  

        System.out.println(

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

        String reqKey = scanner.next();

  

        

        

        System.out.println(

            "Phone number (value): "

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

    



Source link

Leave a Reply

Your email address will not be published.