让开发效率爆表的Guava ---- Maps

时间:2015-06-01 22:52:29   收藏:0   阅读:20065

  本文介绍了Guava集合类Maps的使用, 比如将具有唯一主键的对象快速存入Map等...


package com.wenniuwuren.guava;

import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 
 * @ClassName: MapsTest 
 * @Description: Maps集合类扩展使用 
 * @author wenniuwuren 
 * @date 2015-6-1 下午5:23:22 
 *
 */
public class MapsTest {

	@SuppressWarnings("unchecked")
	public static void main(String[] args) {
		Person p1 = new Person("001", "zhang_san");
		Person p2 = new Person("002", "li_si");
		
		List<Person> personList = Lists.newArrayList();
		personList.add(p1);
		personList.add(p2);
		
		// 将主键当作Map的Key
		Map<String, Person> personMap = Maps.uniqueIndex(personList.iterator(), new Function<Person, String>() {
			@Override
			public String apply(Person input) {
				return input.getId();
			}
			
		});
		System.out.println("将主键当作Map的Key:" + personMap);
		
		
		// 可以说是Maps.uniqueIndex相反的作用
		Set<Person> personSet = Sets.newHashSet(p1, p2);
		@SuppressWarnings("unused")
		Map<Person, String> personAsMap= Maps.asMap(personSet, new Function() {
			@Override
			public Object apply(Object input) {
				return ((Person)input).getId();
			}
		});
		System.out.println(personAsMap);
		
		
		// 转换Map中的value值
		Map<String, String> transformValuesMap = Maps.transformValues(personMap, new Function<Person, String>() {
			@Override
			public String apply(Person input) {
				return input.getName();
			}
		});
		System.out.println("转换Map中的value值" + transformValuesMap);
		
	}
}


class Person {
	private String Id;
	private String name;
	
	public Person(String Id, String name) {
		this.Id = Id;
		this.name = name;
	}
	
	public String getId() {
		return Id;
	}
	public void setId(String id) {
		Id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
	
}


评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!