get string value from HashMap depending on key name

前端 未结 10 2007
误落风尘
误落风尘 2020-11-28 21:39

I have a HashMap with various keys and values, how can I get one value out?

I have a key in the map called my_code, it should contain a str

相关标签:
10条回答
  • 2020-11-28 22:09

    You can use the get(Object key) method from the HashMap. Be aware that i many cases your Key Class should override the equals method, to be a useful class for a Map key.

    0 讨论(0)
  • 2020-11-28 22:11

    map.get(myCode)

    0 讨论(0)
  • 2020-11-28 22:17

    This is another example of how to use keySet(), get(), values() and entrySet() functions to obtain Keys and Values in a Map:

            Map<Integer, String> testKeyset = new HashMap<Integer, String>();
    
            testKeyset.put(1, "first");
            testKeyset.put(2, "second");
            testKeyset.put(3, "third");
            testKeyset.put(4, "fourth");
    
            // Print a single value relevant to a specified Key. (uses keySet())
            for(int mapKey: testKeyset.keySet())
                System.out.println(testKeyset.get(mapKey));
    
            // Print all values regardless of the key.
            for(String mapVal: testKeyset.values())
                System.out.println(mapVal.trim());
    
            // Displays the Map in Key-Value pairs (e.g: [1=first, 2=second, 3=third, 4=fourth])
            System.out.println(testKeyset.entrySet());
    
    0 讨论(0)
  • 2020-11-28 22:17
     HashMap<Integer, String> hmap = new HashMap<Integer, String>();
     hmap.put(4, "DD");
    

    The Value mapped to Key 4 is DD

    0 讨论(0)
提交回复
热议问题