Java如何按Predicate条件过滤Map<String,List<Person>>得到目标集合
正确实现代码
import java.util.AbstractMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; // 过滤条件 Predicate<Person> predicate = p -> p.age > 20; Map<String, List<Person>> result = myVariable.entrySet().stream() // 对每个键对应的列表做过滤 .map(entry -> { List<Person> filteredList = entry.getValue().stream() .filter(predicate) .collect(Collectors.toList()); // Java8 环境请替换为 new AbstractMap.SimpleEntry<>(entry.getKey(), filteredList) return Map.entry(entry.getKey(), filteredList); }) // 排除过滤后列表为空的键值对 .filter(entry -> !entry.getValue().isEmpty()) // 收集为结果Map .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
原代码错误说明
- 拼写错误:泛型声明的
Persin为笔误,正确应为Person - 过滤逻辑错误:
myVariable.keySet(p).stream().anyMatch(predicate)写法错误,keySet()无入参版本,你需要获取当前key对应的List<Person>做匹配,应改为myVariable.get(p).stream().anyMatch(predicate) - 收集器参数错误:
Collectors.toMap第二个参数要求是接收key返回对应value的函数,你原写法直接传入了列表计算逻辑,会抛出类型不匹配错误,需要用lambda包裹为p -> myVariable.get(p).stream().filter(predicate).collect(Collectors.toList())
内容的提问来源于stack exchange,提问作者Pryda
相关产品推荐
相关产品推荐

