[英]Get key of Guava Multimap by index of value
Suppose this is my example data which are in Multimap collection: 假设这是我在Multimap集合中的示例数据:
x -> [1,2]
y -> [1,3]
z -> [4]
then I made a list of values which might be like this:(First column is index of values , second column is value) 然后我列出了一个可能像这样的值列表:(第一列是值的索引,第二列是值)
0 -> 1
1 -> 2
2 -> 1
3 -> 3
4 -> 4
My question is how to get paired key of a value by knowing index of that value. 我的问题是如何通过知道该值的索引来获取该值的配对键。 For example the key for index "2" , the key "y" must return.
例如,索引“ 2”的键,键“ y”必须返回。
If you want to do this one time, you can do simple loop over Multimap#entries()
and maintain counter yourself, but: 如果您想一次执行此操作,则可以对
Multimap#entries()
进行简单循环并自己维护计数器,但是:
Mutlimap
implementations could be different Mutlimap
实现的迭代顺序可能不同 Multimap
here at all, but maintain a list (probably List<Entry<String, Integer>>
). Multimap
,而应该维护一个列表(可能是List<Entry<String, Integer>>
)。 If you really have to have multimap and it's immutable, you could use .entries().asList()
view to achieve what I described above: 如果确实需要
.entries().asList()
并且它是不可变的,则可以使用.entries().asList()
视图来实现我上面所述的内容:
//given
ImmutableListMultimap<String, Integer> multimap =
ImmutableListMultimap.<String, Integer>builder()
.putAll("x", 1, 2)
.putAll("y", 1, 3)
.putAll("z", 4)
.build();
ImmutableList<Map.Entry<String, Integer>> entriesWithPosition =
multimap.entries().asList();
//when
Map.Entry<String, Integer> foundEntry = entriesWithPosition.get(2);
//then
assertThat(foundEntry.getKey()).isEqualTo("y");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.