Storing Multiple Values in a Map--by Tim O'Brien 整理by博主

  当我们需要实现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. 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值