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
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.
map.get(myCode)
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());
HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(4, "DD");
The Value mapped to Key 4
is DD