ForInfinity ForInfinity - 1 year ago 77
Java Question

How to sum up values in a HashMap<String, <String,Integer>>?

I have a following HashMap:

HashMap<String, HashMap<String,Integer>> dataArray = new HashMap<>();

In the program, I do use enhanced loop to iterate few times and insert data into the HashMap, based on some kind of key, as in:

dataArray.get(primaryKey).put(length, totalCost)

It produces the following output:

{123-456-789={00:05:00=500, 00:01:06=220}, 999-090-090={00:08:01=900}}

I use a formula to calculate the
value, but I have to make sure it is set to 0 at each iteration's beginning.

My question is, I want to sum up
values for each
. The end result should be something like this:

{123-456-789={00:06:06=720}, 999-090-090={00:08:01=900}}

How would I accomplish that? Do I have to create another HashMap, or is it possible to modify the ones already existing? With a loop perhaps?

EDIT: Forgot to mention that if I try to obtain existing
value with
, compiler complains about a suspicious call to
and returns

Answer Source

Why so complicated? Just alter your data-structure. OOP is meant to solve precisely that problem. Just store the subtables in an Object each and provide appropriate methods/variables. As for inserting the data into the existing Map: How would you distinguish the resulting sums from what you inserted as standard-values? In addition this would quite likely cause a concurrent modification, though there are ways to work around that.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download