4
votes

Is there a way to increment a value in a map without needing a second variable?

for example, this doesn't work:

counts = new Map<string,integer>();
counts.put('month_total',0);
counts.put('month_total',counts.get['month_total']++);

it returns "Initial term of field expression must be a concrete SObject: MAP"

instead I needed to do:

counts = new Map<string,integer>();
counts.put('month_total',0);
integer temp = 0;
temp++;
counts.put('month_total',temp);

is there any way to increment without needing an extra variable?

2

2 Answers

6
votes

Replace

counts.put('month_total',counts.get['month_total']++);

with

counts.put('month_total',counts.get('month_total')++);
0
votes
List<String> lststrings = new List<String>{'key','wewe','sdsd','key','dfdfd','wewe'};
    Map<String,Integer> mapval = new Map<String,Integer>();
Integer count = 1;
for(string str : lststrings){
    IF(mapval.containsKey(str)){
        mapval.put(str,mapval.get(str)+1);
    }
    else{
        mapval.put(str,count);
    }
}
system.debug('value of mapval'+mapval);