You are on page 1of 2

package Multivaluemap1.

multivaluemap;
import
import
import
import

java.util.Collection;
java.util.Iterator;
java.util.LinkedHashMap;
java.util.LinkedHashSet;

import org.apache.commons.collections4.map.MultiValueMap;
/**
* example of using an apache commons MultiValueMap to store and retrieve
* entries with multiple values per entry
*
* this should produce the following output
key:key1, values=[value1, value2]
value:value1
value:value2
key:key2, values=[value3]
value:value3
* this is dependent on the following:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
*/
public class Multivaluemap {
public static void main(String[] args) {
@SuppressWarnings("unchecked")
MultiValueMap<String, String> orderedMap =
MultiValueMap.multiValueMap(
new LinkedHashMap<String, Collection<String>>(),
(Class<LinkedHashSet<String>>)(Class<?>)LinkedHa
shSet.class
);
orderedMap.put("key1", "value1");
orderedMap.put("key1", "value2");
orderedMap.put("key2", "value3");
Iterator<String> iterator = orderedMap.keySet().iterator();
// iterate over the map
while (iterator.hasNext()) {
String key = iterator.next();
System.out.println("key:" + key + ", values=" + orderedM
ap.get(key));
Collection<String> values = orderedMap.getCollection(key
);

// iterate over the entries for this key in the map


for(Iterator<String> it3 = values.iterator(); it3.hasNex
t();) {
String value = it3.next();
System.out.println("
}
}
}
}

value:" + value);

You might also like