You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Java Stream根据子对象CellPhone的modelNumber过滤Person列表

错误原因

Stream.filter()方法要求传入的断言函数必须返回boolean类型值,你原有代码中内部嵌套的Stream最终调用collect(Collectors.toList())返回的是符合条件的手机集合,类型不匹配所以报错。

正确实现

你可以使用Stream的anyMatch()终端操作替代内层的filter+collect,该操作只要流中存在任意一个元素满足判断条件就会返回true,刚好匹配「只要Person持有指定型号手机就保留」的需求,完整的Stream写法如下:

List<Person> result = persons.stream()
        .filter(p -> p.getPhones().stream()
                .anyMatch(x -> x.getModelNumber().equals(searchModel))
        )
        .collect(Collectors.toList());
// 遍历输出验证结果
result.forEach(p -> System.out.println(p.getName()));

执行后输出的结果就是你预期的John、Doe、Kumar。

内容的提问来源于stack exchange,提问作者user14132461

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 01:21:02