当我们需要实现key和value间的一对多关系时,MultiMap必不可少。
Maven项目使用前,加入下述依赖在你的项目pom.xml中。
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
一个简单MutiMap实例:
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;
/**
*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.
* @author
*
*/
public class MapTest {
public static void main(String[] args) {
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.println("\n");
}
}
}
输出为:
Key: ONE, Value: TEST. Value: HELLO.
Key: TWO, Value: PICNIC. Value: TESTIMONY.
MultiMap的remove机制实例如下:
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.collections.MultiHashMap;
import org.apache.commons.collections.MultiMap;
public class MultiMapExample {
public static void main(String[] args) {
MultiMapExample example = new MultiMapExample( );
example.start( );
}
public void start(){
MultiMap map=new MultiHashMap();
map.put( "ONE", "TEST" );
map.put( "ONE", "WAR" );
map.put( "ONE", "CAR" );
map.put( "ONE", "WEST" );
map.put( "TWO", "SKY" );
map.put( "TWO", "WEST" );
map.put( "TWO", "SCHOOL" );
// At this point "ONE" should correspond to "TEST", "WAR", "CAR", "WEST"
map.remove("ONE","WAR");
map.remove("ONE","CAR");
// The size of this collection should be two "TEST", "WEST"
Collection oneCollection=(Collection)map.get("ONE");
Iterator it=oneCollection.iterator();
while(it.hasNext()){
System.out.println( "One Value: " + it.next( ) + ". " );
}
Collection values=map.values();
Iterator valuesIt=values.iterator();
while(valuesIt.hasNext()){
System.out.println( "Values: " + valuesIt.next( ) + ". " );
}
}
}
结果如下:
One Value: TEST.
One Value: WEST.
Values: TEST.
Values: WEST.
Values: SKY.
Values: WEST.
Values: SCHOOL.