Getting specific values โโin Multimap
I am using Multimap which has two values โโfor each key. Below is the code I use to get each value separately:
The first bit of code gets the first value of the object:
for(Object object : map.get(object))
{
return object
}
Then I use another method to get a different value. This method takes the first object as an argument:
for(Object object : team.get(object))
{
if(object != initialObject)
{
return object;
}
}
This seems like a "hacky" way of doing things, is there a way to make these values โโeasier for me?
+2
source to share
2 answers
Collection<Object> 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<Object> it = values.iterator();
it.next(); // move the pointer to the second object
return it.next(); // get the second object
+2
source to share
If you are using Guava, Iterables#get
you probably want to - it returns the Nth element from any iterable, e.g .:
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// and to return value from position:
return Iterables.get(myMultimap.get(key), position);
If you use ListMultimap
it then it behaves very much like a map to a list so you can call directly get(n)
.
+5
source to share