org.apache.commons.collections – MultiValueMap

Maps, Treemaps and whatever have you, are a great way to store data for easy access the data by a given key. The disadvantage with this objects is that the key has to be unique. This means that you cannot store different values associated with one key.

I needed a solution to store data in a map and each key should be used for multiple values

key = human, value = Batman
key = human, value = Captain America
key = alien, value = Superman

Searching the web, I found org.apache.commons.collections

A MultiMap is similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

This makes it very easy to filter a map by a given key.

package de.eknori.test;

import org.apache.commons.collections.map.MultiValueMap;

public class MultiMap {

	public static void main(String[] args) {

		MultiValueMap superheroes = new MultiValueMap();
		String key = "human";
		superheroes.put("mutant", "Wolverine");
		superheroes.put("mutant", "Beast");
		superheroes.put("alien", "Superman");
		superheroes.put("human", "Batman");
		superheroes.put("human", "Captain America");

		System.out.println(key + " superheroes: " + superheroes.get(key));
		System.out.println("There are " + superheroes.size()
				+ " different kind of superheroes: " + superheroes.keySet());

		System.out.println("All superheroes: " + superheroes.values());
	}
}

Running the code will show the following on the console:

human superheroes: [Batman, Captain America]
There are 3 different kind of superheroes: [alien, mutant, human]
All superheroes: [Superman, Wolverine, Beast, Batman, Captain America]