将 2 张地图的细节同化到第三张地图

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

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

qinhaichao11111 回答:将 2 张地图的细节同化到第三张地图

这样的事情应该可以工作:

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())));
本文链接:https://www.f2er.com/30139.html

大家都在问