Search code examples
javaguava

Retrieving specific values in Multimap


I'm using a Multimap that has two values per key. Below is the code I'm using to get each value separately:

The first bit of code gets the first object value:

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

Then, I'm using another method to retrieve the other 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 'hackish' way of doing things, so is there any way for me to get the values more easily?


Solution

  • 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