如何使用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
相关产品推荐
相关产品推荐

