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

时间:2015-11-22 03:27:11

标签: java dictionary

我有一个对象(extern "C" { #include "libswscale/swscale.h" } ),它显示了每种能量类型的能量使用情况,它有两个字段:

EnergyUsageData

地图包含能源账单数据。 我正在获取能源账单数据并将其列入清单:

private EnergyType type;
private Map<YearMonth, BigDecimal> billsMap;

现在我想将这些地图与具有相同能量类型的地图结合起来。例如,如果柴油能量类型的列表中有多个元素,我想为它们组合List<EnergyUsageData> energyUsageDataList = new ArrayList<>(); 并为相同的billsMap添加能量使用。我正在寻找一种有效的方法来组合数据并生成一个列表,每个能量类型只有一个元素。这样做的最佳方式是什么?

2 个答案:

答案 0 :(得分:2)

伪代码:

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.

答案 1 :(得分:1)

使用Java 8流,你可以像这样高效地完成它。

#include<iostream>
using namespace std;
int main()
{
    char seq[10];
    //initialize the sequence
    for (int i = 0; i<10; i++)
    {
        seq[i] = ' ';
    }
    //read characters from the keyboard
    for (int i = 0; i<10; i++)
    {
        cin.get(seq[i]);
        if (seq[i] == '\0')
        {
            break;
        }
    }
    //the output should be the sequence of characters
    //users typed before
    cout << seq;
    system("pause");
    return 0;
}

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

相关问题