Search code examples
javaarraylisthashmaplinkedhashmap

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. 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


Solution

  • A LinkedHashMap is still a Map, which means that keys are unique. The map simply cannot have two "A" keys at the same time.

    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:

    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]