java - 将第二张地图的细节同化到第三张地图中
问题描述
我有 2 个地图item<String, ItemDetails>
,Price<String , UnitDetails>
对于过滤后的项目列表,我需要将一些价格详细信息填充到另一个地图中
ItemSummary< String, Indent>
插图:
for (Map.Entry<String, ItemDetails> entry : item.entrySet()) {
if("something".equals(entry.getValue().getDescription())
&& "available".equals(entry.getValue().getStock())){
UnitDetails unit = Price.get(entry.getKey());
ItemSummary.put(entry.getKey(), new Indent(unit.getUnit(), unit.getPrice())
}
如何使用流、过滤器和映射来实现这一点
解决方案
像这样的东西应该工作:
ItemSummary<String,Indent> summary =
item.entrySet()
.stream()
.filter(e -> "something".equals(e.getValue().getDescription())
&& "available".equals(e.getValue().getStock()))
.collect(Collectors.toMap(Map.Entry::getKey,
e -> {UnitDetails unit = Price.get(e.getKey());
return new Indent(unit.getUnit(), unit.getPrice());
}));
如果一个UnitDetails
实例包含一个属性,其值与Map<String , UnitDetails>
映射中的对应键相同,您可以使collect
步骤更清晰:
ItemSummary<String,Indent> summary =
item.entrySet()
.stream()
.filter(e -> "something".equals(e.getValue().getDescription())
&& "available".equals(e.getValue().getStock()))
.map(e -> Price.get(e.getKey()))
.collect(Collectors.toMap(Unit::getKey,
u -> new Indent(u.getUnit(), u.getPrice())));
推荐阅读
- logging - 记录器在 Cloudwatch 上创建空日志
- c++ - 我们可以在不使用虚函数的情况下根据它们的参数调用覆盖函数吗?
- parallel-processing - 为什么原子操作仅适用于 HLSL 计算着色器中的线程组?
- ruby-on-rails - 在入口脚本中捆绑安装和纱线安装 - Docker
- php - AJAX 将值从 js 发送到 php
- php - 如何使用 php 删除阿拉伯语文本中的特殊字符(多余的空格)?
- python - 无法在 Jupyter 笔记本中使用预装的 python 包
- python - 在 python 中解析汤
- r - 如何在类网络对象的**超图**中转换矩阵
- react-native - 将 Skype for business 应用程序与 React Native 移动应用程序深度链接