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
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));
//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);
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);
}
Just call get:
HashMap<String, String> map = new HashMap<String, String>();
map.put("x", "y");
String value = map.get("x"); // value = "y"