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

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

问题描述

如果我有值 "foo"HashMap;ftw.containsValue("foo") 返回 true 的 ftw,如何获取对应的键?我必须遍历哈希图吗?最好的方法是什么?

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?

推荐答案

如果您选择使用 Commons Collections 库 而不是标准的 Java Collections 框架,您可以轻松实现这一点.

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

BidiMap 接口是一个双向映射,允许您将键映射到值(如法线映射),也可以将值映射到键,从而允许您执行查找在两个方向.getKey() 方法.

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.

但是有一个警告,双向映射不能将多个值映射到键,因此除非您的数据集在键和值之间具有 1:1 映射,否则您不能使用双向映射.

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 bidi maps.

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

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.

一旦你能确保,使用 entrySet() 方法获取 Map 中的条目(映射)集合.获得类型为 Map.Entry,遍历条目,比较存储值 与预期相反,并获取对应键.

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.

可以在 Google Guava 和重构的 Commons-Collections 库(后者不是 Apache 项目).感谢 Esko 指出 Apache Commons Collections 中缺少的通用支持.将集合与泛型结合使用可使代码更易于维护.

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.

4.0 版以来,官方 Apache Commons Collections™ 库支持 泛型.

Since version 4.0 the official Apache Commons Collections™ library supports generics.

参见 摘要页面org.apache.commons.collections4.bidimap";BidiMapOrderedBidiMapSortedBidiMap 现在支持 Java 泛型的接口.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.

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

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