Search code examples
javaiteratormultimap

Multimap Iterator retrieve multiple values in Java


Is there a way to access each value to assign it to a variable from a java MultiValueMap from Apache commons while iterating? I have one key and two possible values that I would like to extract each iteration that are later written to a table.

Currently the below produces two values for pair.getValue().

public void setValues (MultiValueMap map)
{
    Iterator it = map.entrySet().iterator();
    while (it.hasNext())
    {
        Map.Entry pair = (Map.Entry)it.next();
        String id = pair.getKey().toString();
        String name = pair.getValue().toString();
    }
}

I edited this for clarity, a below suggestion was helpful in using Collection values = map.getCollection(id);


Solution

  • If I understand your question, you want to get the list of values for all keys:

        Iterator it = map.keySet().iterator();
        while (it.hasNext())
        {
            String id = (String)it.next();
            Collection<?> values = map.getCollection(id);
            // loop on values and do whatever you need ...
        }