consider I have a hash map map(two, twooo) and other hash map pun(twooo, 3)
Now i need to get the key "two" from the value "3"
How can I do that?
consider I have a hash map map(two, twooo) and other hash map pun(twooo, 3)
Now i need to get the key "two" from the value "3"
How can I do that?
Assuming that you have a different value for each key, you can do something like this:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
team1.put("1", 1);
team1.put("2", 2)
private String getKey(Integer value){
for(String key : team1.keySet()){
if(team1.get(key).equals(value)){
return key; //return the first found
}
}
return null;
}
In same manner iterate through other hash map to find a key of value which is key in other hashMap.
If you're using HashMap
, this will be very inefficient, you have to loop over the values in both maps to find the key you're looking for, something like:
public static <K1, VK, V2> K1 findKeyInFirstMap(
Map<K1, VK> map1, Map<VK, V2> map2, V2 value) {
VK valueKey = null;
for (Entry<VK, V2> e : map2.entrySet()) {
if (e.getValue().equals(value)) {
valueKey = e.getKey();
break;
}
}
if (valueKey == null) {
throw new IllegalArgumentException(value + " not found in map2");
}
for (Entry<K1, VK> e : map1.entrySet()) {
if (e.getValue().equals(valueKey)) {
return e.getKey();
}
}
throw new IllegalArgumentException(valueKey + " not found in map1");
}
This assumes your maps don't have null
keys or values, but why would you do that to yourself? :)
Much more efficient would be to use a bi-directional mapping, like Guava's BiMap
. With a BiMap
, it's much simpler, and O(1) instead of O(n):
map1.inverse().get(map2.inverse().get(value));
Or, with the same error semantics as the previous method:
public static <K1, VK, V2> K1 findKeyInFirstMap(
BiMap<K1, VK> map1, BiMap<VK, V2> map2, V2 value) {
VK valueKey = map2.inverse().get(value);
if (valueKey == null) {
throw new IllegalArgumentException(value + " not found in map2");
}
K1 key = map1.inverse().get(valueKey);
if (key == null) {
throw new IllegalArgumentException(valueKey + " not found in map1");
}
return key;
}