如何使用Java Streams基于双层嵌套列表属性筛选目标Plan
使用Java Streams实现匹配条件的Plan查找方法
没问题,我来帮你搞定这个需求!咱们可以用Java Streams的filter和anyMatch组合来高效实现,同时还要注意处理集合为null的情况,避免踩空指针的坑。
完整实现代码
import java.util.List; import java.util.Optional; public class PlanProcessor { public static Plan findMatchingPlan(List<Plan> plans, String id) { // 先做输入校验,避免无效操作和空指针 if (plans == null || id == null || id.isBlank()) { return null; } // 用Stream查找第一个符合要求的Plan Optional<Plan> matchingPlan = plans.stream() // 先筛掉没有请求的Plan(requestList为空或null的直接跳过) .filter(plan -> plan.getRequestList() != null && !plan.getRequestList().isEmpty()) // 再筛掉不包含目标请求的Plan .filter(plan -> plan.getRequestList().stream() // 只看未取消的请求 .filter(request -> !request.isCancelled()) // 确保请求有身份列表,不然白忙活 .filter(request -> request.getIdentityList() != null && !request.getIdentityList().isEmpty()) // 检查这个请求里有没有匹配的身份编号 .anyMatch(request -> request.getIdentityList().stream() .anyMatch(identity -> id.equals(identity.getIdNumber())))) // 取第一个匹配的,没有的话就是空Optional .findFirst(); // 把Optional转成Plan,没匹配到就返回null return matchingPlan.orElse(null); } }
代码逻辑拆解
咱们一步步捋清楚这段代码是怎么工作的:
- 输入校验:先检查传入的
plans列表、目标id是不是null或者空白,提前返回null,省得后面做无用功还可能报错。 - 第一层过滤:直接把那些
requestList为null或者空的Plan过滤掉,这些Plan根本不可能有符合条件的请求嘛。 - 第二层过滤:针对每个Plan的请求列表,层层筛选:
- 先挑出没被取消的请求(
!request.isCancelled()),取消的直接跳过。 - 再挑出
identityList不为空的请求,不然遍历空列表也是白搭。 - 用
anyMatch检查:这个请求的身份列表里,有没有哪个Identity的idNumber和目标id完全匹配?只要有一个就算符合条件。
- 先挑出没被取消的请求(
- 获取结果:用
findFirst()拿到第一个符合所有条件的Plan,包装在Optional里,最后用orElse(null)返回——如果没找到匹配的,就返回null。
额外优化小技巧
- 要是你需要返回所有符合条件的Plan,而不是第一个,只需要把
findFirst()改成collect(Collectors.toList()),同时把方法返回类型改成List<Plan>就行。 - 可以把身份匹配的逻辑抽成单独的方法,代码会更清爽,比如:
这样主方法里的过滤逻辑就变成:private static boolean hasMatchingIdentity(Request request, String targetId) { return request.getIdentityList() != null && !request.getIdentityList().isEmpty() && request.getIdentityList().stream() .anyMatch(identity -> targetId.equals(identity.getIdNumber())); }
是不是一眼就能看懂?.filter(plan -> plan.getRequestList().stream() .filter(request -> !request.isCancelled()) .anyMatch(request -> hasMatchingIdentity(request, id)))
内容的提问来源于stack exchange,提问作者Seephor
相关产品推荐
相关产品推荐

