如何用Java Stream筛选List<List<LinkedHashMap<String,String>>>目标子列表
正确的Stream API实现方式
你的代码问题在于外部filter方法需要返回布尔值来判断是否保留当前内部List,但你在其中返回了collect(Collectors.toList())的结果(一个List对象),导致类型不匹配,无法通过编译。
要筛选出包含目标Map的内部List,核心是用anyMatch方法判断内部List中是否存在符合条件的元素,它会直接返回布尔值,正好适配外部filter的需求。
实现代码
1. 获取所有符合条件的内部List
如果需要找出所有包含ID="PdmarticleID"且Value="99945"的Map的内部List:
import java.util.List; import java.util.LinkedHashMap; import java.util.stream.Collectors; // 筛选所有符合条件的内部List List<List<LinkedHashMap<String, String>>> targetLists = productsMasterMap.stream() .filter(innerList -> innerList.stream().anyMatch(map -> // 用常量在前的equals避免空指针 "PdmarticleID".equals(map.get("ID")) && "99945".equals(map.get("Value")) ) ) .collect(Collectors.toList());
2. 获取第一个符合条件的内部List
如果只需要找到第一个符合条件的内部List,用findFirst返回Optional更安全(避免空指针):
import java.util.List; import java.util.LinkedHashMap; import java.util.Optional; // 获取第一个符合条件的内部List Optional<List<LinkedHashMap<String, String>>> firstTargetList = productsMasterMap.stream() .filter(innerList -> innerList.stream().anyMatch(map -> "PdmarticleID".equals(map.get("ID")) && "99945".equals(map.get("Value")) ) ) .findFirst(); // 处理结果示例 firstTargetList.ifPresent(list -> { // 对找到的内部List执行后续操作 System.out.println("找到目标List:" + list); });
关键说明
anyMatch:遍历内部List,只要找到一个符合条件的Map就返回true,是判断集合是否包含目标元素的高效方式。- 常量在前的
equals写法:避免map.get("ID")为null时抛出NullPointerException。
内容的提问来源于stack exchange,提问作者user1107888
相关产品推荐
相关产品推荐

