Java Hashmap:如何从价值中获取密钥? [英] Java Hashmap: How to get key from value?

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

问题描述

如果我的值foo,并且 HashMap< String> ftw 其中 ftw.containsValue(foo)返回 true ,我怎么能得到相应的密钥?我必须循环散列图吗?如果您选择使用

.apache.org / collections /rel =noreferrer> Commons Collections library ,而不是标准的Java Collections API,您可以轻松实现。



BidiMap 界面Collections库是一个双向映射,允许您将键映射到值(如法线贴图),还可以将值映射到键,从而允许您在两个方向上执行查找。获取值的关键是由 getKey()方法

尽管如此,双向映射不能将多个值映射到键,因此除非您的数据集在键和值之间具有1:1映射,否则您不能使用bidimaps。

更新



如果您想依赖Java Collections API,则必须在将值插入到映射中时确保键和值之间的1:1关系。这很容易,说起来容易做起来难。



一旦你可以确保,使用 entrySet()方法来获取Map中的一组条目(映射)。一旦获得了地图。条目,迭代条目,比较存储值与预期值进行比较,并获取对应的键

更新#2



可以在 Google Guava 中找到对带有泛型的比例地图的支持,重构 Commons-Collections 库(后者不是Apache项目)。感谢Esko指出Apache Commons Collections中缺少的通用支持。使用带泛型的集合可以创建更多可维护的代码。

If I have the value "foo", and a HashMap<String> ftw for which ftw.containsValue("foo") returns true, how can I get the corresponding key? Do I have to loop through the hashmap? What is the best way to do that?

解决方案

If you choose to use the Commons Collections library instead of the standard Java Collections API, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidimaps.

Update

If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.

Update #2

Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.

这篇关于Java Hashmap:如何从价值中获取密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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