I have this batch class with many records that gives the count of records associated with each fieldName.

Now Iam trying to insert those fieldName and count values as a new record in a custom object.

For that I need the exact count values, since with each batch my count value changes and not add up. I need a way to do it.

Iam using database.stateful with my map valsToInsert

            for(String AccfieldName : fieldList) {
                system.debug('count accounts where ' +AccfieldName+ ' is not null ' + recordListbyFieldMap.get(AccfieldName));
                valsToInsert.put(AccfieldName, recordListbyFieldMap.get(AccfieldName));
                    if(valsToInsert.containsKey(AccfieldName)) {
                        valstoInsert.put(AccfieldName, recordListbyFieldMap.get(AccfieldName) + recordListbyFieldMap.get(AccfieldName));

What logic should be used so that the value of map gets added up , like first batch chunk gave 2000 count, next gave 1500 so it should keep adding up like 3500 for that field.

2 Answers 2


You need to get the old value (if any), out of the map before setting the new value. This was mostly an "order of operations" problem in your code. Here's a revised version:

for(String AccfieldName : fieldList) {
    Integer totalCount = valsToInsert.get(AccfieldName);
    Integer newCount = recordListbyFieldMap.get(AccfieldName);
    if(totalCount == null) {
        totalCount = 0;
    if(newCount == null) {
        newCount = 0;
    totalCount += newCount;
    valsToInsert.put(AccfieldName, totalCount);
  • Working as expected. Thanks a lot @sfdcfox
    – CcMda
    Commented Aug 18, 2021 at 11:56
  • Hey @sfdcfox When Iam trying to Insert these records, Iam facing with : Too many DML Rows 10001 for (Integer acc : valsToInsert.values()) { for(String fieldNames : valsToInsert.keyset()) { metadata_information__c newRecord = new metadata_information__c(); newRecord.Object_name__c = 'Account'; newRecord.Field_Name__c = fieldNames; newRecord.Count__c = acc; addRecordList.add(newRecord); } } Then i have INSERTED the list, am i doing it wrong ?
    – CcMda
    Commented Aug 18, 2021 at 13:46

The map needs to be defined as static, on the class level, not in the execute method. Then you can use the same map in every execution. And you don't need stateful. Something like this.

public class SUSE_AccountBatch implements Database.Batchable<SObject> {
    Map<Object, Object> objectMap = new Map<Object, Object>();

    public void execute(Database.BatchableContext bc, List<SObject> scope) {
  • They are trying to track values across multiple execute calls. Are you sure you've understood the question properly?
    – sfdcfox
    Commented Aug 18, 2021 at 11:08
  • i understand that he needs to have same map reference across all batch executions
    – Damecek
    Commented Aug 18, 2021 at 11:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .