在Multimap中检索特定值

我正在使用每个键有两个值的Multimap。 下面是我用来分别获取每个值的代码:

第一个代码获取第一个对象值:

for(Object object : map.get(object)) { return object } 

然后,我正在使用另一种方法来检索其他值。 此方法将第一个对象作为参数:

 for(Object object : team.get(object)) { if(object != initialObject) { return object; } } 

这似乎是一种“hackish”做事方式,所以有没有办法让我更容易获得价值?

 Collection values = map.get(key); checkState(values.size() == 2, String.format("Found %d values for key %s", values.size(), key)); return values.iterator().next(); // to get the first Iterator it = values.iterator(); it.next(); // move the pointer to the second object return it.next(); // get the second object 

如果您正在使用Guava, Iterables#get可能就是您想要的 – 它从任何可迭代的返回Nth项,例如:

 Multimap myMultimap = ArrayListMultimap.create(); // and to return value from position: return Iterables.get(myMultimap.get(key), position); 

如果您正在使用ListMultimap那么它的行为非常类似于List的映射,因此您可以直接调用get(n)