Java 映射,从值到键
有什么方法可以获取与映射中已知值关联的键吗?通常你知道键并且想要获取值,但我想做相反的事情,从值到键。是否可以?
Is there any way to get a key associated with a known value in a map? Normally you know the key and you want to get the value, but I want to do the opposite, going from value to key. Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,您必须迭代映射中的值,然后将每个键存储在列表中:
或者您可以使用 双向地图,但请注意:
Yes, you have to iterate over the values in the map and then store each key in a list:
Or you could use a bidirectional map, though do note:
好吧,我不是 Google 项目 LambdaJ 方面的专家,但它确实提供了一些很酷的替代方案。
假设您有一张包含该月所有日期的地图:
那么我们可以轻松实现您想要的目标,如下所示:
或者甚至是一些更有趣的搜索,例如:
Well, I am not an expert on Google Project LambdaJ, but it certainly offers a few cool alternatives.
Supposing you have a map with all the days of the month:
Then we could easily achieve what you want like this:
Or even a few more interesting searches like:
无需迭代所有键来查找值,您可以使用 Apache Commons BidiMap
Without iterating all the keys looking for the value you can use an Apache Commons BidiMap
映射是一个数学条目,并不意味着可以进行反向映射。也就是说,如果每个映射值都是唯一的,您也许能够创建“反向”映射。当然,您必须将所有数据操作封装在适当更新两个映射的方法中。
如果每个映射值都不唯一,那么您需要创建值到键列表的反向映射。
最后,如果您不关心快速访问,您可以迭代整个 Map 来查找值。由于您需要值和键,因此最好迭代 Map.Entry 项。
您选择使用的技术在很大程度上取决于以速度换取内存占用是否更好。通常,由于对值进行哈希处理,因此拥有额外的映射会更快,但会消耗额外的内存。对 Map.Entry 进行循环速度较慢,但占用的内存较少。
A Map is a mathematical entry which doesn't imply that a reverse mapping is possible. That said you might be able to create a "reverse" mapping if every mapped value is unique. Naturally, you'll have to encapsulate all the data manipulations in methods that update both Maps appropriately.
If every mapped value is not unique, then you need to create a reverse mapping of a value to a list of keys.
Finally, if you don't care about fast access, you can iterate over the entire Map looking for Values. Since you'll need both the Value and the Key, it is probably best to iterate over the Map.Entry items.
The technique you choose to use will depend heavily on whether it is better to trade speed for memory footprint. Generally having an extra Map is faster due to the hashing being done on the Value(s), but costs extra memory. Having a loop over the Map.Entry(s) is slower, but costs less memory.
在这里他们已经讨论了双向地图。如今,Guava (https://github.com/google/guava) 提供了一个很好的 BiMap,您可以使用它可以用于此目的:
https://github.com/google/guava/wiki/ NewCollectionTypesExplained#bimap
Here they already talked about Bidirectional maps. Nowadays, Guava (https://github.com/google/guava) offers a nice BiMap that you can use for that purpose:
https://github.com/google/guava/wiki/NewCollectionTypesExplained#bimap