在 Lambda 表达式中组合谓词

Combining Predicates within Lambda Expression

这是一个由两部分组成的问题。

我有一个布尔字段和几个 String[] 字段,我需要为每个字段评估谓词。

以下代码获取每个设备的接口。然后我想根据谓词评估这些接口。

  1. 有没有更有效的方法?
  2. .filter(predicates.stream().reduce(Predicate::or) 给出了这个错误: 我不确定如何解决。

        parentReference.getDevices().stream().parallel().filter(ASA_PREDICATE).forEach((device) -> {
        List<Predicate<? super TufinInterface>> predicates = new ArrayList();
    
        if (iName != null) {
            Predicate< ? super TufinInterface> iNameFilter = myInterface -> Arrays.stream(iName)
                    .allMatch(input -> myInterface.getName().toLowerCase().contains(input.toLowerCase()));
            predicates.add(iNameFilter);
        }
        if (ipLow != null) {
            Predicate< ? super TufinInterface> ipLowFilter = myInterface -> Arrays.stream(ipLow)
                    .allMatch(input -> myInterface.getName().toLowerCase().contains(input.toLowerCase()));
            predicates.add(ipLowFilter);
        }
        if (ip != null) {
            Predicate< ? super TufinInterface> ipFilter = myInterface -> Arrays.stream(ip)
                    .allMatch(input -> myInterface.getName().toLowerCase().contains(input.toLowerCase()));
            predicates.add(ipFilter);
        }
        if (zone != null) {
            Predicate< ? super TufinInterface> zoneFilter = myInterface -> Arrays.stream(zone)
                    .allMatch(input -> myInterface.getName().toLowerCase().contains(input.toLowerCase()));
            predicates.add(zoneFilter);
        }            
    
        try {
            ArrayList<TufinInterface> tufinInterfaces = Tufin.GET_INTERFACES(parentReference.user, parentReference.password, parentReference.hostName, device)
                    .stream()
                    .filter(predicates.stream().reduce(Predicate::or)
                            .orElse(t->true)).parallel().collect(Collectors.toCollection(ArrayList<TufinInterface>::new));
            interfaces.addAll(tufinInterfaces);
        } catch (IOException | NoSuchAlgorithmException | KeyManagementException | JSONException | Tufin.IncompatibleDeviceException ex) {
            Logger.getLogger(InterfaceCommand.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    });
    

Stream 有一个名为 anyMatch 的函数,可以稍微清理一下您的过滤器。

ArrayList<TufinInterface> tufinInterfaces = Tufin.GET_INTERFACES(parentReference.user, parentReference.password, parentReference.hostName, device)
                .stream()
                .filter(s -> predicates.stream().anyMatch(pred -> pred.test(s)))
                .collect(Collectors.toList());