首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何合并两个Hashmap并对相同键的值求和?

如何合并两个Hashmap并对相同键的值求和?
EN

Stack Overflow用户
提问于 2015-11-22 11:27:11
回答 2查看 659关注 0票数 0

我有一个对象(EnergyUsageData),它表示每种能源类型的能源使用情况,它有两个字段:

代码语言:javascript
运行
复制
private EnergyType type;
private Map<YearMonth, BigDecimal> billsMap;

该地图包含能源账单数据。我正在获取能源账单数据,并将其放入一个列表中:

代码语言:javascript
运行
复制
List<EnergyUsageData> energyUsageDataList = new ArrayList<>();

现在我想为那些具有相同能量类型的人组合贴图。例如,如果我在柴油能源类型的列表中有多个元素,我想组合它们的billsMap,并添加相同YearMonth的能源使用情况。我正在寻找一种有效的方法来组合数据并生成一个列表,其中每个能源类型只有一个元素。做这件事最好的方法是什么?

EN

回答 2

Stack Overflow用户

发布于 2015-11-22 12:47:14

伪码:

代码语言:javascript
运行
复制
For all keys in table 2
  v2 = that key's value in table 2.
  v1 = that key's value in table 1.
  If v1 is null
    Set key and v2 pair into table 1.
  Otherwise
    Sum the two values
    Set key and sum pair in table 1.
Done.
票数 2
EN

Stack Overflow用户

发布于 2015-11-22 14:35:21

使用Java 8 streams,您可以像这样高效地完成这项工作。

代码语言:javascript
运行
复制
public static List<EnergyUsageData> process(final Collection<EnergyUsageData> data) {
    final Map<EnergyType, Map<YearMonth, BigDecimal>> tempMap = new HashMap<>();
    final List<EnergyUsageData> energyUsageData = data.stream()
            .flatMap(d -> d.getBillsMap().entrySet().stream().map(
                    dd -> new FlatData(d.getType(), dd.getKey(), dd.getValue())))
            .filter(d -> {
                final Map<YearMonth, BigDecimal> map = tempMap.get(d.type);
                if (map != null) {
                    final BigDecimal amount = map.get(d.yearMonth);
                    map.put(d.yearMonth, amount.add(d.amount));
                    return false;
                }
                return true;
            })
            .map(d -> {
                final HashMap<YearMonth, BigDecimal> billsMap = new HashMap<>();
                billsMap.put(d.yearMonth, d.amount);
                tempMap.put(d.type, billsMap);
                return new EnergyUsageData(d.type, billsMap);
                //Assuming Constructor of EnergyUsageData will hold
                // the reference of billsMap and will not copy billsMap
            })
            .collect(Collectors.toList());
    return energyUsageData;
}

final class FlatData {
    public final EnergyType type;
    public final YearMonth yearMonth;
    public final BigDecimal amount;

    FlatData(EnergyType type, YearMonth yearMonth, BigDecimal amount) {
        this.type = type;
        this.yearMonth = yearMonth;
        this.amount = amount;
    }
}

它将一个接一个地处理值,并在整个集合中循环一次。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33851292

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档