Manuel Hernandez Manuel Hernandez - 1 month ago 6
Java Question

How to get a key from a HashMap, Map in Java

I have posted the Java code below How can I get at the key from the value hm. There seems to be no way to extract the key the way one can in other languages Dictionary types.

Ideally hm.getKey() would be awesome but I don't believe that is a method available in Java.

I am looking for a singular key to a singular HashMap.Other similar questions revolved around iteration. Also I do not want to use external libraries.

. Thanks

/* Begin Java Code */
import java.util.Map;
import java.util.HashMap;

public class SimpleMap
{

public static void main(String args[])
{
Map<String, String> hm = setMap("a", "b");
System.out.println(hm);
/*how could I get the key from hm here?*/

}
public static Map<String, String> setMap(String firstVal, String secondVal)
{
Map<String, String> keyVal = new HashMap<String, String>();
keyVal.put(firstVal, secondVal);
return keyVal;
}
}

/* End Java Code */


Console Command: $ java SimpleMap

Output {a=b}

Answer
// To get set of keys use
Set s = hm.keySet();
// to get values from key
String value = hm.get("a");
// to get both key,value pair
Set<Map.Entry<String, String>> s = hm.entrySet();
for (Map.Entry<String, String> e : s) {
    System.out.println(e.getKey()+","+e.getValue());
}