简体   繁体   English

从Guava Multimap中的值返回键

[英]Return key from value in Guava Multimap

In my Java code, I need to be able to figure out the key from a value. 在我的Java代码中,我需要能够从值中找出密钥。 I know how to do it vice versa, and I have used that many times in my code, but is there a way I could get the key while only knowing the value in Guava Multimap? 我知道怎么做反之亦然,我已经在我的代码中使用了很多次,但是有一种方法可以获得密钥而只知道Guava Multimap中的值吗? Thanks in advance. 提前致谢。

Guava supplies an inversion method for Multimap . Guava为Multimap提供了一种反演方法。 See Multimaps.invertFrom . 请参见Multimaps.invertFrom

This might do fine for you if you don't frequently need the inversion, or if your multimap is small. 如果您不经常需要反演,或者您的multimap很小,这可能对您没问题。 But this inversion is an expensive process. 但这种反转是一个昂贵的过程。 You can likely gain some efficiency by simply maintaining both forward and reverse as suggested by JB Nizet in comments. 根据JB Nizet在评论中的建议,您可以通过简单地保持正向和反向来获得一些效率。 Both however can be multimaps to allow for non-uniqueness. 然而,两者都可以是多重映射以允许非唯一性。

使用ImmutableMultimap,您可以调用ImmutableMultimap.inverse()

use BiMap, https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html 使用BiMap, https: //google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html

then, 然后,

bimap.inverse().get(value)

will give you the key. 会给你钥匙。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM