stream流中的filter优雅写法

1.定义工厂类

  1. 内部集成静态方法,返回Predicate 的接口
  2. 如果是stream流中遍历的对象,不需要定义到方法的参数签名那
static class ResourceDetailPredicates {
        public static Predicate<ResourceDetail> wareNameFilter() {
            return resourceDetail1 -> {
                if (resourceDetail1.getAppCnName().contains("关闭")){
                    return false;
                }
                if (resourceDetail1.getAppCnName().contains("禁用")){
                    return false;
                }
                if (resourceDetail1.getAppCnName().contains("关仓")){
                    return false;
                }
                return true;
            };
        }

        public static Predicate<ResourceDetail> platformFilter(ScanObjParam param) {
            return resourceDetail1 -> {
                if(CollectionUtils.isEmpty(param.getPlatforms())){
                    return true;
                }else {
                    return param.getPlatforms().contains(resourceDetail1.getAppPlatform());
                }
            };
        }

        public static Predicate<ResourceDetail> envFilter(ScanObjParam param) {
            return resourceDetail1 -> {
                if(StringUtils.isBlank(param.getEnv())){
                    return true;
                }else {
                    return param.getEnv().equalsIgnoreCase(resourceDetail1.getEnvType());
                }
            };
        }
    }

2.使用工厂类

List<ResourceDetail> resourceDetailList = resourceDetails.stream()
    .filter(ResourceDetailPredicates.platformFilter(param))
    .filter(ResourceDetailPredicates.envFilter(param))
    .filter(ResourceDetailPredicates.wareNameFilter())
    .collect(Collectors.toList());
posted @ 2024-05-20 17:57  SpecialSpeculator  阅读(20)  评论(0编辑  收藏  举报