让开发效率爆表的Guava ---- Range范围过滤

  本文介绍了Guava中Range的使用, 使用Range和Guava的函数式编程可以用少量代码实现指定范围内容的过滤。


import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Range;


/**
 * Guava Range类使用
 * Created by wenniuwuren on 2015/6/3.
 */
public class RangeTest {
	public static void main(String[] args) {

		Range<Integer> numberRange = Range.closed(1, 10);

		System.out.println("closed包含边界" + numberRange.contains(10) + " ," + numberRange.contains(1));

		Range<Integer> numberOpenRange = Range.open(1, 10);

		System.out.println("open不包含边界" + numberOpenRange.contains(1) + ", " + numberOpenRange.contains(10));

		Range<Integer> atLeast = Range.atLeast(10);
		System.out.println("大于等于边界的所有值" + atLeast);

		Range<Integer> lessThan = Range.lessThan(10);
		System.out.println("小于等于边界的所有值" + lessThan);

		/**
		 *  过滤掉不符合内容Range范围的
		 */
		Range<Integer> ageRange = Range.closed(35,50);
		Function<Person,Integer> ageFunction = new Function<Person,
				Integer>() {
			@Override
			public Integer apply(Person person) {
				return person.getAge();
			}
		};
		Person p1 = new Person("zhangsan", 50);
		Person p2 = new Person("lisi", 70);

		Predicate<Person> predicate = Predicates.compose(ageRange, ageFunction);

		System.out.println("是否包含zhangsan:" + predicate.apply(p1)
						+ ", 是否包含lisi:" + predicate.apply(p2));
	}
}

class Person {
	private String name;
	private Integer age;

	public Person(String name, Integer age) {
		this.name = name;
		this.age = age;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}






}




输出结果:




参考资料: 

                《Getting Started with Google Guava》

你可能感兴趣的:(guava,函数式编程,range)