码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-03 17:36:56      阅读:210      评论:0      收藏:0      [点我收藏+]

标签: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范围过滤

标签:guava   range   函数式编程   

原文地址:http://blog.csdn.net/wenniuwuren/article/details/46348601

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!