java 如何根据哈希图的值获取密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11795777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get key depending upon the value from hashmap
提问by Rajhrita
I want to retrieve the specific key associated with the value in a hashmap
我想检索与哈希图中的值关联的特定键
I want to retrieve the key of "ME", how can I get it?
我想找回“ME”的钥匙,怎么才能拿到呢?
Code snippet :
代码片段:
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,"I");
map.put(2,"ME");
回答by Tom
There's a small problem with what you are trying to do. There can be multiple occurrences of the same value in a hashmap, so if you look up the key by value, there might be multiple results (multiple keys with the same value).
您尝试执行的操作存在一个小问题。哈希图中可以多次出现相同的值,因此如果按值查找键,可能会出现多个结果(多个键具有相同的值)。
Nevertheless, if you are sure this won't occur, it can be done; see the following example:
不过,如果您确定这不会发生,则可以做到;请参阅以下示例:
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(5, "vijf");
map.put(36, "zesendertig");
}
static Integer getKey(HashMap<Integer, String> map, String value) {
Integer key = null;
for(Map.Entry<Integer, String> entry : map.entrySet()) {
if((value == null && entry.getValue() == null) || (value != null && value.equals(entry.getValue()))) {
key = entry.getKey();
break;
}
}
return key;
}
}
回答by kgautron
Iterate over the entries of the map :
迭代地图的条目:
for(Entry<Integer, String> entry : map.entrySet()){
if("ME".equals(entry.getValue())){
Integer key = entry.getKey();
// do something with the key
}
}
回答by baraber
/**
* Return keys associated with the specified value
*/
public List<Integer> getKey(String value, Map<Integer, String> map) {
List<Integer> keys = new ArrayList<Integer>();
for(Entry<Integer, String> entry:map.entrySet()) {
if(value.equals(entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
回答by Anthony Accioly
回答by bharris9
You will have to iterate through the collection of keys to find your value.
您必须遍历键的集合才能找到您的值。
Take a look at this post for details: Java Hashmap: How to get key from value?
有关详细信息,请查看这篇文章:Java Hashmap:如何从值中获取键?