CollectionUtils利用Predicate实现Collection的快速操作

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

 

 

 

转载于:https://my.oschina.net/zimingforever/blog/1615870

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值