使用值从HashMap获取密钥 [英] Get key from a HashMap using the value

查看:145
本文介绍了使用值从HashMap获取密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用值获取HashMap的键。

  hashmap = new HashMap< String,Object> ); 

haspmap.put(one,100);
haspmap.put(two,200);

这意味着我需要一个值为100的函数, p>

似乎这里有很多问题要求同样的事情,但他们不为我工作。





如何做?

解决方案

HashMap中的put方法定义如下:

  Object put(Object key,Object value)

键是第一个参数,因此在您的put中,one是键。你不能容易地在HashMap中查找值,如果你真的想这样做,它将是一个线性搜索通过调用 entrySet(),像这样:

  for(Map.Entry< Object,Object> e:hashmap.entrySet()){
Object key = e.getKey();
对象值= e.getValue();
}

然而,这是O HashMap除非你只需要做很少。如果你真的希望能够通过键或值来频繁地查找,核心Java没有任何东西,但类似BiMap从谷歌集合是你想要的。


I want to get the key of a HashMap using the value.

hashmap = new HashMap<String, Object>();

haspmap.put("one", 100);
haspmap.put("two", 200);

Which means i want a function that will take the value 100 and will return the string one.

It seems that there are a lot of questions here asking the same thing but they don't work for me.

Maybe because i am new with java.

How to do it?

解决方案

The put method in HashMap is defined like this:

Object  put(Object key, Object value) 

key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like this:

for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
    Object key = e.getKey();
    Object value = e.getValue();
}

However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.

这篇关于使用值从HashMap获取密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆