简体   繁体   English

总结数组列表中对象的值(Java)

[英]Sum up values of object in Array List (Java)

I have key/value like this我有这样的键/值

("A", 2.2);
("A", 1.1);
("B", 4.0);
("B", 2.0);
("C", 2.5);
("A", 2.0);
("A", 2.2);
("A", 1.0);

I expect to have result is我希望结果是

A=3.3
B=6.0
C=2.5
A=5.2

I tried with code我试过代码

           static LinkedHashMap<String, Double> map = new LinkedHashMap<String, Double>();
    public static void putAndIncrement(String key, double value) {
        Double prev = map.get(key);
        Double newValue = value;
        if (prev != null) {
            newValue += prev;
        }
        double roundOff = Math.round(newValue * 10.0) / 10.0;
        map.put(key,roundOff);

    }

However result is然而结果是

A=8.5
B=6.0
C=2.5

Hashmap, Map, LinkedHashmap is not right way to get my expecting result. Hashmap, Map, LinkedHashmap 不是获得我预期结果的正确方法。 Can you consult me any other method for this situation ?对于这种情况,您可以向我咨询任何其他方法吗? Please help me how to get that or any suggestion is really helpful for me.请帮助我如何获得那个或任何建议对我真的很有帮助。 Thank you谢谢

A LinkedHashMap is still a Map , which means that keys are unique . LinkedHashMap仍然是Map ,这意味着键是唯一的 The map simply cannot have two "A" keys at the same time.地图根本不能同时有两个"A"键。

If you want to sum up the values of consecutive keys, you need to use a List with a class for storing the key/value pair:如果要对连续键的值求和,则需要使用带有类的List来存储键/值对:

static List<KeyValue> list = new ArrayList<>();
public static void putAndIncrement(String key, double value) {
    KeyValue keyValue = (list.isEmpty() ? null : list.get(list.size() - 1));
    if (keyValue == null || ! key.equals(keyValue.getKey())) {
        list.add(new KeyValue(key, value));
    } else {
        keyValue.addValue(value);
    }
}
public final class KeyValue {
    private final String key;
    private double value;
    public KeyValue(String key, double value) {
        this.key = key;
        this.value = value;
    }
    public void addValue(double value) {
        this.value += value;
    }
    public String getKey() {
        return this.key;
    }
    public double getValue() {
        return this.value;
    }
    @Override
    public String toString() {
        return this.key + "=" + this.value;
    }
}

Test测试

putAndIncrement("A", 2.2);
putAndIncrement("A", 1.1);
putAndIncrement("B", 4.0);
putAndIncrement("B", 2.0);
putAndIncrement("C", 2.5);
putAndIncrement("A", 2.0);
putAndIncrement("A", 2.2);
putAndIncrement("A", 1.0);
System.out.println(list);

Output输出

[A=3.3000000000000003, B=6.0, C=2.5, A=5.2]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM