使用值从HashMap获取密钥
我想使用该值获取HashMap的键。
hashmap = new HashMap(); haspmap.put("one", 100); haspmap.put("two", 200);
这意味着我想要一个值为100的函数,并返回一个字符串。
似乎这里有很多问题要求同样的事情,但它们对我不起作用。
也许是因为我是java新手。
怎么做?
HashMap中的put方法定义如下:
Object put(Object key, Object value)
key是第一个参数,所以在你的put中,“one”是关键。 你不能轻易地在HashMap中查找值,如果你真的想这样做,那就是通过调用entrySet()
完成线性搜索,如下所示:
for (Map.Entry
然而,这是O(n)并且有点破坏了使用HashMap的目的,除非你只需要很少这样做。 如果您真的希望能够经常按键或值查找,核心Java没有任何东西可供您使用,但Google Collections中的BiMap就是您想要的。
我们可以从VALUE
获得KEY
。 以下是示例代码_
public class Main { public static void main(String[] args) { Map map = new HashMap(); map.put("key_1","one"); map.put("key_2","two"); map.put("key_3","three"); map.put("key_4","four");
System.out.println(getKeyFromValue(map,"four")); } public static Object getKeyFromValue(Map hm, Object value) { for (Object o : hm.keySet()) { if (hm.get(o).equals(value)) { return o; } } return null; } }
我希望这对每个人都有帮助。
- 如果只需要,只需使用
put(100, "one")
。 请注意,键是第一个参数,值是第二个。 - 如果您需要能够同时获取键和值,请使用
BiMap
(来自番石榴)
您混合了键和值。
Hashmap hashmap = new HashMap(); hashmap.put(100, "one"); hashmap.put(200, "two");
之后一个
hashmap.get(100);
会给你“一个”
你反过来了。 100应该是第一个参数(它是键),“one”应该是第二个参数(它是值)。
阅读HashMap的javadoc,这可能对您有所帮助: HashMap
要获取该值,请使用hashmap.get(100)
。
public class Class1 { private String extref="MY"; public String getExtref() { return extref; } public String setExtref(String extref) { return this.extref = extref; } public static void main(String[] args) { Class1 obj=new Class1(); String value=obj.setExtref("AFF"); int returnedValue=getMethod(value); System.out.println(returnedValue); } /** * @param value * @return */ private static int getMethod(String value) { HashMap hashmap1 = new HashMap(); hashmap1.put(1,"MY"); hashmap1.put(2,"AFF"); if (hashmap1.containsValue(value)) { for (Map.Entry e : hashmap1.entrySet()) { Integer key = e.getKey(); Object value2 = e.getValue(); if ((value2.toString()).equalsIgnoreCase(value)) { return key; } } } return 0; } }
如果你通过100给予什么获得“ONE”那么
初始化哈希映射
hashmap = new HashMap
haspmap.put(100,"one");
并通过hashMap.get(100)
检索值
希望有所帮助。
如果您不一定要使用Hashmap,我建议使用pair
看看这个http://www.cplusplus.com/reference/utility/pair/
我在这里使用它: http : //codeforces.com/contest/507/submission/9531943