如何使用Java流基于双嵌套列表中的属性过滤集合

时间:2018-04-26 22:56:43

标签: java collections java-stream

我正在尝试更好地理解如何使用Java流。我有这些课程:

public class Plan {

    List<Request> requestList;
}

public class Request {

    List<Identity> identityList;
    boolean isCancelled;

}

public class Identity {

    String idNumber;
}

我正在尝试编写一个方法,该方法返回包含具有匹配标识号的未取消请求的计划。

这就是我的尝试:

public static Plan findMatchingPlan(List<Plan> plans, String id) {
    List<Plan> filteredPlan = plans.stream()
            .filter(plan -> plan.getRequestList().stream()
                    .filter(request -> !request.isCancelled())
                    .filter(request -> request.getIdentityList().stream()
                        .filter(identity -> identity.getIdNumber().equals(id))))
            .collect(Collectors.toList());
}

这给了我一个错误:

java.util.stream.Stream<com.sandbox.Identity> cannot be converted to boolean

我理解为什么会有错误。嵌套过滤器返回一个不能作为布尔值计算的过滤器。问题是,我不知道自己错过了什么。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

假设你希望第一个匹配Plan,可以这样做,使用lambda表达式:

public static Plan findMatchingPlan(List<Plan> plans, String id) {
    return plans.stream()
                .filter(plan -> plan.getRequestList()
                                    .stream()
                                    .filter(request -> ! request.isCancelled())
                                    .flatMap(request -> request.getIdentityList().stream())
                                    .anyMatch(identity -> identity.getIdNumber().equals(id)))
                .findFirst()
                .orElse(null);
}

或者像这样,使用方法引用,找到匹配Plan任何

public static Plan findMatchingPlan(List<Plan> plans, String id) {
    return plans.stream()
                .filter(plan -> plan.getRequestList()
                                    .stream()
                                    .filter(request -> ! request.isCancelled())
                                    .map(Request::getIdentityList)
                                    .flatMap(List::stream)
                                    .map(Identity::getIdNumber)
                                    .anyMatch(id::equals))
                .findAny()
                .orElse(null);
}