首页 > 解决方案 > 将第二张地图的细节同化到第三张地图中

问题描述

我有 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())
        }

如何使用流、过滤器和映射来实现这一点

标签: javajava-8

解决方案


像这样的东西应该工作:

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())));

推荐阅读