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

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

问题描述

我想使用 value 获取 HashMap 的 key.

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);

这意味着我想要一个取值 100 并返回字符串 1 的函数.

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.

也许是因为我是 java 新手.

Maybe because i am new with java.

怎么做?

推荐答案

HashMap中的put方法是这样定义的:

The put method in HashMap is defined like this:

Object  put(Object key, Object value) 

key 是第一个参数,所以在你的说法中,one"是关键.在 HashMap 中你不能轻易地按值查找,如果你真的想这样做,这将是通过调用 entrySet() 完成的线性搜索,如下所示:

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();
}

然而,这是 O(n) 并且有点违背了使用 HashMap 的目的,除非你只需要很少这样做.如果您真的希望能够频繁地通过键或值进行查找,那么核心 Java 对您没有任何帮助,但您想要的是来自 Google Collections 的 BiMap.

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天全站免登陆