google guava小例子

package com.cdg.guava;

import java.util.List;
import java.util.Map;

import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;

public class Test03 {

	public static void main(String[] args) {

		Map<String, String> eurPriceMap = Maps.newHashMap();
		eurPriceMap.put("aaa", "111");
		//过滤MAP
		Map<String, String> usdPriceMap = Maps.transformValues(eurPriceMap,
				new Function<String, String>() {
					@Override
					public String apply(String value) {
						System.out.println(value);
						return null;
					}
				});

		System.out.println(usdPriceMap);

		List<Person> persons = Lists.newArrayList(new Person("aaa"),
				new Person("ddd"), new Person("ccc"), new Person("null"));
		//List排序
		List<Person> sortedCopy = new Ordering<Person>() {
			@Override
			public int compare(Person left, Person right) {
				return left.getLastName().compareTo(right.getLastName());
			}
		}.immutableSortedCopy(persons);

		for (Person p : sortedCopy) {
			System.out.println(p.getLastName());
		}

		//过滤List
		List<Person> newList = Lists.transform(sortedCopy, new Function<Person, Person>() {
			@Override
			public Person apply(Person value) {
				//如果返回空则list里面有个空值,长度是sortedCopy的长度,for循环时可能会抛空异常
				return Strings.isNullOrEmpty(value.getLastName()) ? value : null ;
			}
		});
		System.out.println("\n"+newList.size());
		for (Person p : newList) {
			//这里必须要判断是否为空
			if(p != null){
				System.out.println(p.getLastName());
			}
		}
	}

}

class Person {
	Person(String lastName) {
		this.lastName = lastName;
	}

	private String lastName;

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}
}

发布了52 篇原创文章 · 获赞 12 · 访问量 22万+

猜你喜欢

转载自blog.csdn.net/caodegao/article/details/44981533