简体   繁体   English

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

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

I'm trying to filter a list of objects say BOLReference based on a key which is present in the inner object of one of the List of Objects of this BOLReference.我正在尝试根据此 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();

While doing so I'm getting error as:这样做时出现错误:

Cannot convert from Stream<WorkFlowExceptions> to boolean

My BOLReference looks like below:我的 BOLReference 如下所示:

private String ediTransmissionId;
private List<WorkflowExceptions> workflowExceptions;

And my WorkflowExceptions looks like:我的 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();

Failing anyMatch I think.我认为anyMatch都失败了。

A filter clause does not return a boolean but a stream. This causes a problem because your first filter expects a boolean result, but gets a stream from the second filter.过滤器子句不返回 boolean,而是返回 stream。这会导致问题,因为您的第一个过滤器需要 boolean 结果,但从第二个过滤器得到 stream。 You can use anyMatch instead to achieve the desired result.您可以改用anyMatch来获得所需的结果。

You can make stream expressions more readable by formatting them on more lines and extracting complex logic into methods.您可以使 stream 表达式更具可读性,方法是在更多行上格式化它们并将复杂的逻辑提取到方法中。

You could fix & refactor it like this:您可以像这样修复和重构它:

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

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

And:和:

public class BOLReference {

    // ...

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

And:和:

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