使用guava Predicates工具类优雅处理Stream流的filter方法

         现在对于集合操作时,我都是使用Stream来进行操作的,感觉贼好用,对于map操作时,一般使用方法引用就能解决,如

gradeList.stream()
    .map(RegionGradeViewForm::getRegionId)
    .map(String::valueOf)
    .collect(toList());

         Stream流配合方法引用写的代码看着就舒服,所以用久了就不想看见箭头符号,但是在操作filter的时候,因为需要进行复杂的判断,方法引用就不适用了,如这样的代码

studentList.stream()
    .filter(student -> !hasTemperatures.contains(student.getStudentId()))
    .sorted(Comparator.comparing(StudentEntity::getStudentClass))
    .collect(toList());
Map<Integer, String> gradeNameByClassIdCache = classList.stream()
    .filter(classView ->{
        if(classView.getClassLevelId() == null){
            return false;
        }
        return true;
    })
    .collect(toMap(ClassViewForm::getClassId, classView ->{
         Integer levelId = classView.getClassLevelId();
        return gradeNameCache.get(String.valueOf(levelId));
    }));

        用的多了感觉不美观,发现guava Predicates工具类能够优雅解决这个问题

        对于第一个式子

studentList.stream()        
    .filter(Predicates.compose(hasTemperatures::contains, StudentEntity::getStudentId).negate())
    .sorted(Comparator.comparing(StudentEntity::getStudentClass))
    .collect(toList());

         对于第二个式子

Map<Integer, String> gradeNameByClassIdCache = classList.stream()
    .filter(Predicates.compose(Objects::isNull, ClassViewForm::getClassLevelId).negate())
    .collect(toMap(ClassViewForm::getClassId, classView ->{
        Integer levelId = classView.getClassLevelId();
        return gradeNameCache.get(String.valueOf(levelId));
    }));

        我感觉在Stream流操作集合时,尽量使用方法引用进行操作,这样使得代码简短,还美观,相应的Predicates类的方法还有多少,这里就不一一介绍了,只要熟悉Predicate接口的同学应该看一眼就知道怎么用了。 

        另外guava还提供了Functions工具类,来处理Function接口的方法,这个也可以在Stream流中进行操作,下次再进行Stream操作时,可以先留意这两个类。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值