commons-collections集合类型-MultiMap

在日常的开发工作中,我们有的时候需要构造像Map<K, List<V>>或者Map<K, Set<V>>这样比较复杂的集合类型的数据结构,如果是自己写,需要额外大量的代码,此时,就可以使用到commons-collections里面的MultiMap

代码如下

首先加入依赖:

<dependency>
	<groupId>commons-collections</groupId>
	<artifactId>commons-collections</artifactId>
	<version>3.2.2</version>
</dependency>

package org.osc.hazelcast.coll;

import java.util.HashMap;
import java.util.HashSet;

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

public class MultiMapTest 
{
	static void list()
	{
		/**
		 * 默认是取出来的是list
		 */
		MultiMap mm = new MultiValueMap();
		mm.put("唐朝", new User("1", "李渊"));
		mm.put("唐朝", new User("2", "李世民"));
		mm.put("唐朝", new User("3", "李治"));
		mm.put("唐朝", new User("4", "李显"));
		mm.put("唐朝", new User("4", "李旦"));
		
		mm.put("宋朝", new User("5", "赵匡胤"));
		mm.put("宋朝", new User("6", "赵光义"));
		
		System.out.println(mm.get("唐朝"));
		System.out.println(mm.get("唐朝").getClass());
	}
	
	static void set()
	{
		/**
		 * 如果取出来的是set , 需要调用decorate方法
		 */
		MultiMap mm = MultiValueMap.decorate(new HashMap<String, User>(), HashSet.class);
		mm.put("唐朝", new User("1", "李渊"));
		mm.put("唐朝", new User("2", "李世民"));
		mm.put("唐朝", new User("3", "李治"));
		mm.put("唐朝", new User("4", "李显"));
		mm.put("唐朝", new User("4", "李旦"));
		
		mm.put("宋朝", new User("5", "赵匡胤"));
		mm.put("宋朝", new User("6", "赵光义"));
		
		System.out.println(mm.get("唐朝"));
		System.out.println(mm.get("唐朝").getClass());
	}
	
	public static void main(String[] args)
	{
		list();
		System.out.println("-----------------");
		set();
	}

}
class User
{
	private String id;
	private String name;
	public int hashCode() {
		return id.hashCode();
	}
	public boolean equals(Object obj)
	{
		User user = (User)obj;
		return this.id.equals(user.id);
	}
	public User(String id, String name)
	{
		this.id = id;
		this.name = name;
	}
	public String toString()
	{
		return "User [id=" + id + ", name=" + name + "]";
	}
}

运行,输出如下:

[User [id=1, name=李渊], User [id=2, name=李世民], User [id=3, name=李治], User [id=4, name=李显], User [id=4, name=李旦]]
class java.util.ArrayList
-----------------
[User [id=1, name=李渊], User [id=2, name=李世民], User [id=3, name=李治], User [id=4, name=李显]]
class java.util.HashSet

你可能感兴趣的:(commons-collections集合类型-MultiMap)