如何用Java Stream API筛选地址编号匹配指定列表的Location对象
问题解决:过滤Location列表匹配指定门牌号
场景说明
现有以下领域类:
public class Location { GPS gps; Address address; // 其他字段 } public class Address { String street; String number; // 其他字段 }
同时拥有两个列表:
List<String> houseNumbers:存储目标门牌号的字符串列表List<Location> locations:需要过滤的Location对象列表
需求是:只保留Location.address.number与houseNumbers中任意元素匹配的Location对象。
错误代码分析
你之前尝试的代码存在两个问题:
List<Location> filteredLocations = locations.stream() .anyMatch(location -> housenumbers.stream().anyMatch(location.address.number) );
- 参数类型不匹配:
anyMatch方法需要接收一个Predicate断言函数,但你直接传入了字符串location.address.number,这就导致了编译错误:expecting a Predicate <? super java.lang.String> instead of a String。 - 返回值类型错误:
anyMatch返回的是boolean值,无法直接赋值给List<Location>类型的变量。
正确实现方式
使用stream的filter方法结合列表的contains方法,即可简洁实现需求:
List<Location> filteredLocations = locations.stream().filter( location -> houseNumbers.contains(location.address.number) ).collect(Collectors.toList());
代码说明
stream().filter(...):对locations流中的每个元素进行筛选,仅保留满足断言条件的元素houseNumbers.contains(location.address.number):判断当前Location对象的门牌号是否存在于目标门牌号列表中collect(Collectors.toList()):将过滤后的流转换为List集合,得到最终的结果列表
内容的提问来源于stack exchange,提问作者midi
相关产品推荐
相关产品推荐

