Predicate是一个接口,用于实现一个evaluate的方法,并返回是否符合evaluate条件的值,多用于函数式编程中的快捷操作,CollectionUtils中有大量包含一个Predicate参数的方法,可以实现collection的快捷操作,这里对常用的几个方法做一个简单说明
public class Test {
public static void main(String args[]){
List<Integer> testList=new ArrayList<Integer>(){
{
add(1);
add(2);
add(3);
}
};
//返回testlist且只包含数据大于2
CollectionUtils.filter(testList, itm->{
return Integer.valueOf(itm.toString())>2;
});
//返回testlist符合条件的个数
// int resultMatchNum=CollectionUtils.countMatches(testList,itm->{
// return Integer.valueOf(itm.toString())>1;
// });
//判断testlist是否包含符合条件的元素
// boolean resultExists=CollectionUtils.exists(testList, itm->{
// return Integer.valueOf(itm.toString())>2;
// });
//返回testlist中符合条件的数据,注意只返回一条
// Object reusltFindObject=CollectionUtils.find(testList, itm->{
// return Integer.valueOf(itm.toString())>1;
// //返回唯一一个值
// });
//返回符合条件的collection
// Collection resultSelect=CollectionUtils.select(testList, itm->{
// return Integer.valueOf(itm.toString())>1;
// });
//和select结果相反,返回不符合条件的collection
// Collection resultSelectReject=CollectionUtils.selectRejected(testList, itm->{
// return Integer.valueOf(itm.toString())>1;
// });
//这个比较难理解,如果后面predicate都满足,则返回testlist,官方文档为Returns a predicated (validating) collection backed by the given collection.
// Collection resultCollect=CollectionUtils.predicatedCollection(testList, itm->{
// //Returns a predicated (validating) collection backed by the given collection.
// return Integer.valueOf(itm.toString())>0;
// });
}
}
当然常用的predicate也可以通过PredicateUtils构造出来,比如
//返回为null的collection数据
CollectionUtils.filter(testList, PredicateUtils.nullPredicate());
参考文档 http://blog.csdn.net/scgaliguodong123_/article/details/45874503