2

I've got a Map that I want to iterate over and increment some of the field values of the account. Is it possible to simply set one field value or do I need to instantiate a new Account with similar values and put that into the map to replace the existing values?

Map<Id,Account> accMap = new Map<Id,Account>([Select Id, Field1, Field2 From Account]);
for(Id key : accMap.keyset()){
    accMap.get(key).Field1+1; //Can I do something like this or some similar syntax?

    //Or do I have to put a "new" entry into the Map like this?
    Account a = new Account(
        Id = key,
        Field1 = accMap.get(key).Field1+1,
        Field2 = accMap.get(key).Field2
    );
    accMap.put(key,a);
}

The second option would certainly work, but would be a pain to maintain if I'm incrementing multiple fields at the same time.

2

You can do:

Account a = accMap.get(key);
a.Field1 += 1;
a.Field2 += 1;
...

so you don't need to replace the object.

Or more simply just use the values from the map:

for(Account a : accMap.values()) {
    a.Field1 += 1;
    a.Field2 += 1;
    ...
}

If any of the fields might be null you need to check for that e.g.:

a.Field1 = a.Field1 != null ? a.Field1 + 1 : 1;

or better add a method that performs that logic.

(A special case where a new object is needed is if you want to do an update in an "after" trigger.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.