How to increment a value in a map with Apex?

Zath picture Zath · Jul 11, 2013 · Viewed 10.5k times · Source

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?

Answer

Jeremy Ross picture Jeremy Ross · Jul 11, 2013

Replace

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

with

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