[英]Find a key of a value which is a key in other hashmap
consider I have a hash map map(two, twooo) and other hash map pun(twooo, 3) 考虑我有一个哈希映射图(two,twooo)和其他哈希映射双关语(twooo,3)
Now i need to get the key "two" from the value "3" 现在我需要从值“ 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: 如果您使用的是HashMap
,那么效率将非常低下,您必须遍历两个映射中的值以找到所需的键,例如:
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? 假设您的地图没有null
键或值,但是为什么要自己做呢? :) :)
Much more efficient would be to use a bi-directional mapping, like Guava's BiMap
. 更有效的方法是使用双向映射,例如Guava的BiMap
。 With a BiMap
, it's much simpler, and O(1) instead of O(n): 使用BiMap
,它要简单得多,用O(1)代替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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.