java - 根据条件合并两个列表并使用 java 8 将结果推送到地图
问题描述
我有两个列表源和目标想要根据某些条件合并它们并将数据推送到 Hashmap。我尝试了下面的代码,但我无法成功。
public List<Persona> fetchCommonPersonas(List<User> sourceList,
List<User> targetList) {
final Map<String, String> map = new HashMap<>();
map = sourceList.stream()
.filter(source -> targetList.stream().anyMatch(destination -> {
if(destination.getAge().equals(source.getAge())) {
map.put(source.getUserId(), destination.getUserId());
}
}
));
}
解决方案
这是一种方法:
Map<String, String> map =
sourceList.stream()
.map(source -> targetList.stream()
.filter(dest -> dest.getUserId().equals(source.getUserId()))
.map(dest -> new SimpleEntry<>(source.getPersonaId(), dest.getPersonaId()))
.firstFirst())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
您为源列表的每个元素找到目标列表的相应元素,将这些元素映射到Map.Entry
包含两个人员 ID 的 a ,并将所有条目收集到 a Map
。
推荐阅读
- python - Flask多个参数如何在从一个url查询数据库的多个列时避免多个if语句
- python - 如果在程序运行时重新启动,使用 configparser 写入 .ini 文件会导致一个空文件
- reactjs - 当 div 在 React 中可见时,如何自动滚动到 div?
- spring-boot - Spring Boot 2.2.2 - Prometheus 无法在 Actuator 中工作
- python - django 2.2.8 中的密码重置确认页面 404 错误
- c - 为什么编译器会做这个除法
- swift - 我想将 CoreData 中的数据显示到表格视图中
- amazon-web-services - 代理内存繁重的 POST 请求的最佳 AWS 服务(Elastic Beanstalk/ECS/EC2)是哪个?
- wpf - XAML 文本框中的“TextAlignment”和“HorizontalContentAlignment”有什么区别?
- c - 调用函数时显示相同的随机数