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;
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值