pocockn pocockn - 3 months ago 27
Java Question

Add number in map java

I am creating a function that loops through a string, separates it by comma and then takes the key from the second item in the array and the value from the 1st after splitting the string.

I then want to place these values in a map. This works perfectly, however if i have two strings with the same key it doesn't add the value up it just replaces it.

For example if my string was

123,totti 100,roma, 100,totti

I would want

totti 223
roma 100

Here is my code

private void processCallLogs(String[] splitCalls) {
for (String individualCall : splitCalls) {
int duration = 0;
String[] singleCall = individualCall.split(",");
duration += DurationParser.returnDuration(singleCall[0]);
this.cost += CalculateCost.calculateCostPerCall(singleDuration);
if (totalCallDurations.containsKey(singleCall[1])) {
totalCallDurations.put(singleCall[1], singleDuration);
} else {
totalCallDurations.put(singleCall[1], duration);



You can replace the if with something like this:

if (totalCallDurations.containsKey(singleCall[1])) {
    duration += totalCallDurations.get(singleCall[1]);    
totalCallDurations.put(singleCall[1], duration);