我正在尝试更好地理解如何使用 Java 流。我有这些类(class):
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
我有点理解为什么会出现错误。嵌套过滤器返回一个不能被评估为 boolean 值的过滤器。问题是,我不知道我错过了什么。
如有任何帮助,我们将不胜感激。
最佳答案
假设您希望首先匹配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);
}
关于java - 如何使用 Java 流根据双嵌套列表中的属性过滤集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50052996/