繁体   English   中英

无法从 Stream 转换<t>至 boolean</t>

[英]Cannot convert from Stream<T> to boolean

我正在尝试根据此 BOLReference 的对象列表之一的内部 object 中存在的键来过滤 BOLReference 对象列表。

List<BOLReference> bolRef = complianceMongoTemplate.find(findQuery, BOLReference.class);

Optional<BOLReference> bref = bolRef.stream().filter(br -> br.getWorkflowExceptions().stream()
                        .filter(bk -> bk.getBusinessKeyValues().get(businessKey)
                        .equalsIgnoreCase("ABCD1234"))).findFirst();

这样做时出现错误:

Cannot convert from Stream<WorkFlowExceptions> to boolean

我的 BOLReference 如下所示:

private String ediTransmissionId;
private List<WorkflowExceptions> workflowExceptions;

我的 WorkflowExceptions 看起来像:

private String category;
private Map<String,String> businessKeyValues;
Optional<BOLReference> bref = bolRef.stream()
    .filter(br -> 
        br.getWorkflowExceptions().stream()
            .anyMatch(bk ->
                bk.getBusinessKeyValues().get(businessKey)
                    .equalsIgnoreCase("ABCD1234")))
    .findFirst();

我认为anyMatch都失败了。

过滤器子句不返回 boolean,而是返回 stream。这会导致问题,因为您的第一个过滤器需要 boolean 结果,但从第二个过滤器得到 stream。 您可以改用anyMatch来获得所需的结果。

您可以使 stream 表达式更具可读性,方法是在更多行上格式化它们并将复杂的逻辑提取到方法中。

您可以像这样修复和重构它:

String businessKey = null;
String targetValue = "ABCD1234";

Optional<BOLReference> bref = bolReferences.stream()
    .filter(br -> br. hasBusinessKey(businessKey, targetValue))
    .findFirst();

和:

public class BOLReference {

    // ...

    public boolean hasBusinessKey(String key, String value) {
        return getWorkflowExceptions().stream()
            .anyMatch(wfe -> wfe.hasBusinessKey(key, value));
    }
}

和:

public class WorkflowExceptions {

    // ...

    public boolean hasBusinessKey(String key, String value) {
        return getBusinessKeyValues().get(key).equalsIgnoreCase(value);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM