Java 8 in action代码总结 1 - filter、Predicate接口

本文介绍了Java 8中如何使用filter方法进行集合过滤,并探讨了自定义Predicate接口和使用JDK8内置的Predicate接口进行行为参数化的实践。文章通过示例展示了filter方法的调用以及Predicate接口的方法,如test、negate等,强调了Predicate接口在代码中的作用。
摘要由CSDN通过智能技术生成

调用filter方法过滤目标集合

//调用filter的代码
//filter方法中ApplePredicate接口当作参数传入,
//在调用filter方法的时候则需要传入这个接口的具体实现,对应接口内的方法也要重写;具体的过滤也在filter重写方法的内部实现
List<Apple> apples = filter(inventory, new ApplePredicate() {
   
	@Override
	public boolean test(Apple a) {
   
		return a.getWeight() > 119;
	}
});
System.out.println(apples);

自定义的Predicate接口 和 filter方法

  • 自定义Predicate接口的抽象方法的参数为最后具体要过滤和比较的对象
  • filter方法的参数是Predicate接口,以及需要过滤的集合或者数组
public static List<Apple> filter(List<Apple> inventory, ApplePredicate p){
   
	List<Apple> result = new ArrayList<>();
	for(Apple apple : inventory){
   
		if(p.test(apple)){
   
			result.add(apple);
		}
	}
	return result;
}   

interface ApplePredicate{
   
	public boolean test(Apple a);
}   

总结:这边接口作为参数,是行为参数化的体现,是java8 in action中chapter 2的主题 - Passing code with behavior parameterization

JDK8自带的Predicate(谓词)接口

jdk8自带的Predicate接口,用来代替上面的自定义的谓词接口。
该接口中定义了test,negate,or ,and,isEqual等方法。
当调用这个接口的时候,我们需要先定义一个filter()方法,传入Collection操作对象,根据所要做的操作,传入适当个数的Predicate作为参数。

调用代码

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值