Get keys from HashMap in Java
One of most likely situation we seek is get keys of values from HashMap. While iterating through HashMap, there might be different scenarios as how mapping of key to value is done.
We’ll discuss and see how we can get key/s of value/s of below mentioned pattern-
- Key to Value: Many to One (Many keys with same value)
- Key to Value: One to One (Every Key has unique value)
Lets see an example demonstrating both scenarios
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package code2succeed.com.getkeys; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class GetKeys { @SuppressWarnings({ "rawtypes", "unchecked" }) public static void main(String[] args) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("Key1", "Value1"); hm.put("Key2", "Value2"); hm.put("Key3", "Value2"); hm.put("Key4", "Value2"); hm.put("Key5", "Value3"); hm.put("Key6", "Value4"); System.out.println("Key Value pair stored in HashMap are: "); System.out.println(hm+"\n"); //In case of multiple values i.e. many to one mapping //Value for which Key is to be searched String valueforkeysearch = "Value2"; // Set where unique key will be stored HashSet keyforvalue = new HashSet(); Set entryset = hm.entrySet(); Iterator itr = entryset.iterator(); while(itr.hasNext()){ Map.Entry me = (Entry) itr.next(); if(me.getValue().equals(valueforkeysearch)){ keyforvalue.add(me.getKey()); } } //Print all the key corresponding to value System.out.println("Keys corrosponding to "+valueforkeysearch+" are "+keyforvalue); //In case of multiple values i.e. one to one mapping //Value for which Key is to be searched String uniquevalueforKeysearch = "Value3"; Set uniqueentryset = hm.entrySet(); Iterator uniqueitr = uniqueentryset.iterator(); while(uniqueitr.hasNext()){ Map.Entry uniqueme = (Entry) uniqueitr.next(); if(uniqueme.getValue().equals(uniquevalueforKeysearch)){ //Print key corresponding to value System.out.println("Key corrosponding to "+uniquevalueforKeysearch+" is "+uniqueme.getKey()); } } } } |
Output:
1 2 3 4 5 |
Key Value pair stored in HashMap are: {Key2=Value2, Key1=Value1, Key6=Value4, Key5=Value3, Key4=Value2, Key3=Value2} Keys corrosponding to Value2 are [Key2, Key4, Key3] Key corrosponding to Value3 is Key5 |
Stay tuned for more updates!