[英]How to filter collection based on property within double nested list using Java streams
我正在嘗試更好地理解如何使用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
我有點理解為什么會有錯誤。 嵌套過濾器返回一個不能作為布爾值計算的過濾器。 問題是,我不知道我錯過了什么。
任何幫助,將不勝感激。
假設你想要第一個匹配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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.