bhavna raghuvanshi
bhavna raghuvanshi

Reputation: 1075

Search a value for a given key in a HashMap

How do you search for a key in a HashMap? In this program, when the user enters a key the code should arrange to search the hashmap for the corresponding value and then print it.

Please tell me why it's not working.

import java.util.HashMap;

import java.util.; import java.lang.;

public class Hashmapdemo  
{
    public static void main(String args[]) 
    { 
        String value; 
        HashMap hashMap = new HashMap(); 
        hashMap.put( new Integer(1),"January" ); 
        hashMap.put( new Integer(2) ,"February" ); 
        hashMap.put( new Integer(3) ,"March" ); 
        hashMap.put( new Integer(4) ,"April" ); 
        hashMap.put( new Integer(5) ,"May" ); 
        hashMap.put( new Integer(6) ,"June" ); 
        hashMap.put( new Integer(7) ,"July" );  
        hashMap.put( new Integer(8),"August" );  
        hashMap.put( new Integer(9) ,"September");  
        hashMap.put( new Integer(10),"October" );  
        hashMap.put( new Integer(11),"November" );  
        hashMap.put( new Integer(12),"December" );

        Scanner scan = new Scanner(System.in);  
        System.out.println("Enter an integer :");  
        int x = scan.nextInt();  
        value = hashMap.get("x");  
        System.out.println("Value is:" + value);  
    } 
} 

Upvotes: 24

Views: 106200

Answers (4)

Ambreen Zubari
Ambreen Zubari

Reputation: 77

To decalare the hashMap use this:

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

To enter the elements in the HashMap:

 hm.put(1,"January");
 hm.put(2,"Febuary");

before searching element first check that the enter number is present in the hashMap for this use the method containsKey() which will return a Boolean value:

 if(hm.containsKey(num))
 {
    hm.get(num);
 }

Upvotes: 4

Gagan Prajapati
Gagan Prajapati

Reputation: 142

//If you want the key to be integer then you will have to declare the hashmap //as below :

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "x");
map.put(1, "y");
map.put(2, "z");

//input a integer value x

String value = map.get(x);

Upvotes: -1

Tim B&#252;the
Tim B&#252;the

Reputation: 63814

You wrote

HashMap hashMap = new HashMap();
...
int x = scan.nextInt();
value = hashMap.get("x");

must be:

Map<Integer, String> hashMap = new HashMap<Integer, String>();
...
int x = scan.nextInt();
value = hashMap.get(x);

EDIT or without generics, like said in the comments:

int x = scan.nextInt();
value = (String) hashMap.get(new Integer(x));

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1503469

Just call get:

HashMap<String, String> map = new HashMap<String, String>();
map.put("x", "y");

String value = map.get("x"); // value = "y"

Upvotes: 44

Related Questions