需要让HashMap在键中添加(求和)多个值

时间:2012-11-27 20:49:00

标签: jsf hashmap addition

我试图让一个按钮在同一个输入框中处理多个输入。我有16个输入框,每个输入框都有自己的id#(YfProduct),我用它作为我的hashmap的关键字。对于输入值,我有权重。用户将输入他们想要的任何双重,无论他们想要多少输入框,然后单击一个按钮(a4j:commandButton)激活下面的方法。

private HashMap<Integer, Double> storeWeight = new HashMap<Integer, Double>(); 

public void storeWeight(Yieldfl yieldfl){
    for (YieldItem row : yielditem) {
    storeWeight.put(row.getYfProduct(), row.getWeight());
    System.out.print(storeWeigt)}
}

现在,此代码将使用右键设置适当的值,并使用输入的新输入和另一个按钮单击替换这些值。但是,我要做的是让bean保存以前的值,并总结下一个使用具有相同键的前一个条目输入的值。因此,在用户输入结束时,HashMap将包含16个键,其中为每个键添加了各个值的总和。没有一些严重的硬编码,我无法想出办法。非常感谢。

1 个答案:

答案 0 :(得分:0)

所以这实际上是一个简单的解决方案,我会把解决方案放在这里,只是因为有人遇到了类似的问题。这是我第一次使用HashMap,所以我有一位同事帮帮我。我需要值来调用密钥。

storeWeight.put(row.getYfProduct(), storeWeight.get(row.getYfProduct() + (row.getWeight()));

并避免空指针:

public void storeWeight(Yieldfl yieldfl){
    for (YieldItem row : yielditem) {
        Double oldValue = storeWeight.get(row.getYfProduct());
        if (oldValue == null)
            oldValue = 0.0;
    storeWeight.put(row.getYfProduct(), oldValue + (row.getWeight()));
    row.setWeight(0.0);
    System.out.print(storeWeight);}
}