-2

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

Parabol
  • 63
  • 8
  • 3
    The sum of the A's *is* 8.5. Why wouldn't you expect it to be 8.5? You can't get two different values for the A's if you put them in a map like that. – David Conrad Nov 24 '20 at 02:08
  • Why should the program add the 5.2 to a new 'A' variable instead of the original A value? It will automatically add to original A value. It's a function, so that one domain can only be with one codomain, not two. Otherwise how would the program reference the two unique codomains? – ChilliPenguin Nov 24 '20 at 02:10
  • @ChilliPenguin I know That's why i need your help to find another method rather than use Hashmap , Map or LinkedHashmap – Parabol Nov 24 '20 at 02:31

1 Answers1

3

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]
Andreas
  • 154,647
  • 11
  • 152
  • 247