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);
}
}
HashMap get() Method in Java get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
Use the get() method to get the value associated with a given key. Above, the key is Frames and we are fetching the value associated with it.
HashMap containsValue() Method in Java HashMap. containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the HashMap. It takes the Value as a parameter and returns True if that value is mapped by any of the key in the map.
If your hashmap contain unique key to unique value mapping, you can maintain one more hashmap that contain mapping from Value to Key. In that case you can use second hashmap to get key.
Just call get
:
HashMap<String, String> map = new HashMap<String, String>();
map.put("x", "y");
String value = map.get("x"); // value = "y"
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With