java 当我们知道 HashMap 中的值时获取密钥
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11566039/
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
Getting the key when we know the value in HashMap
提问by London guy
Possible Duplicate:
Java Hashmap: How to get key from value?
可能的重复:
Java Hashmap:如何从值中获取键?
I know that a HashMap contains a particular integer variable as value. How can I get the key associated with this value?
我知道 HashMap 包含一个特定的整数变量作为值。如何获取与此值关联的键?
回答by Paulius Matulionis
This code will do that:
这段代码将做到这一点:
public List<Object> getKeysFromValue(Map<?, ?> hm, Object value){
List <Object>list = new ArrayList<Object>();
for(Object o:hm.keySet()){
if(hm.get(o).equals(value)) {
list.add(o);
}
}
return list;
}
回答by Jonathan Payne
Here you go:
干得好:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test
{
public static void main( String args[] )
{
Map < Integer , Integer > map = new HashMap < Integer , Integer >();
map.put( 1 , 2 );
map.put( 3 , 4 );
map.put( 5 , 6 );
map.put( 7 , 4 );
List< Integer > keys = new ArrayList< Integer >();
Integer value = 4;
for ( Integer key : map.keySet() )
{
if ( map.get( key ).equals( value ) )
{
keys.add( key );
}
}
System.out.println( value + " has been found in the following keys: " + keys );
}
}
The output is:
输出是:
4 has been found in the following keys: [7, 3]
回答by Ramesh PVK
Set<Map.Entry> entries = hashMap.entrySet();
for(Map.Entry entry : entries) {
if(entry.getValue().equals(givenValue)) {
return entry.getKey();
}
}
回答by Kumar Bibek
Hashmaps help you to find the value if you know the key. IF you really want the key from the value, you will have to iterate through all the items, compare the values, and then get the key.
如果您知道密钥,哈希图可帮助您找到值。如果您真的想要值中的键,则必须遍历所有项目,比较值,然后获取键。
回答by Andrey.Pushin
Loop over the entrySet is faster, because you don't query the map twice for each key.
遍历 entrySet 更快,因为您不会为每个键两次查询映射。
public Set<Object> getKeysFromValue(Map<Object, Integer> map, int value) {
Set<Object> keys = new HashSet<Object>();
for (Map.Entry<Object, Integer> entry:map.entrySet()) {
//if value != null
if (entry.getValue() == value) {
keys.add(entry.getKey());
}
}
return keys;
回答by Kumar Vivek Mitra
Try this....short and sweet way...
试试这个......简短而甜蜜的方式......
HashMap<String, Integer> list = new HashMap<String,Integer>();
for (Map.Entry<String, Integer> arr : list.entrySet()){
System.out.println(arr.getKey()+" "+arr.getValue());
}