5.10. Storing Multiple Values in a Map
Problem
You need to store multiple
values for a single key in a
Map
. Instead of a one-to-one relationship between
keys and values, you need a Map
that provides
one-to-many relationships between keys and values.
Solution
Use a MultiMap
. A
MultiMap
maintains a collection of values for a given key. When a new
key/value pair is added to a MultiMap
, the value
is added to the collection of values for that key. The
MultiMap
also provides a way to remove a specific
key/value pair. The following example demonstrates the use of
MultiMap
:
import org.apache.commons.collections.MultiMap; import org.apache.commons.collections.MultiHashMap; MultiMap map = new MultiHashMap( ); map.put( "ONE", "TEST" ); map.put( "TWO", "PICNIC" ); map.put( "ONE", "HELLO" ); map.put( "TWO", "TESTIMONY" ); Set keySet = map.keySet( ); Iterator keyIterator = keySet.iterator( ); while( keyIterator.hasNext( ) ) { Object key = keyIterator.next( ); System.out.print( "Key: " + key + ", " ); Collection values = (Collection) map.get( key ); Iterator valuesIterator = values.iterator( ); while( valuesIterator.hasNext( ) ) { System.out.print( "Value: " + valuesIterator.next( ) + ". " ); } System.out.print( "\n" ); }
Each key in a MultiMap
corresponds to a collection
of values. This example produces the following output while iterating
through all values for each key:
Key: ONE, Value: TEST. Value: HELLO Key: TWO, Value: PICNIC. Value: Testimony
Discussion
In a traditional Map
, a key is removed ...
Get Jakarta Commons Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.