Search a value for a given key in a HashMap

前端 未结 4 1093
余生分开走
余生分开走 2021-02-05 06:51

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

相关标签:
4条回答
  • 2021-02-05 07:30

    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));
    
    0 讨论(0)
  • 2021-02-05 07:33

    //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);
    
    0 讨论(0)
  • 2021-02-05 07:35

    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);
     }
    
    0 讨论(0)
  • 2021-02-05 07:49

    Just call get:

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("x", "y");
    
    String value = map.get("x"); // value = "y"
    
    0 讨论(0)
提交回复
热议问题