Sorry for the beginner question -- I'm generating a Map<ID,String> where the ID is an OpportunityId and the String is the value of a custom field on the Opportunity that I want updated. How would I go about updating the records via the contents of the map?

  • 1
    Please update this question with your existing code so that we can quickly identify problem and propose better solution
    – Himanshu
    Sep 20, 2016 at 18:27

2 Answers 2


You can do it like this:

// Your map
Map<Id, String> m = new Map<Id, String>();

// Update needs to know the type so create objects of the right type
Opportunity[] updates = new Opportunity[] {};
for (Id id : m.keySet()) {
    updates.add(new Opportunity(Id = id, FieldName__c = m.get(id)));
update updates;

Note that there is also a put(String fieldName, Object value) method available so if you didn't want to hard code the field name you could use that to set the value by name.

  • what is this declaring: Opportunity[] updates = new Opportunity[] {}; ? thanks
    – jaw999
    Jun 8, 2017 at 18:10
  • @jaw999 That is exactly the same as List<Opportunity> updates = new List<Opportunity>(); but using the more compact (and interchangeable) array syntax.
    – Keith C
    Jun 9, 2017 at 8:14

The put method of maps update an item when it finds the item: From the documentation: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_map.htm

"If the map previously contained a mapping for this key, the old value is returned by the method and then replaced."

Here you have an example:

Note: myList is String and myMap is String, Integer

List myList = new List();

Map myMap = new Map();
for (String item : myList)
    if (myMap.containsKey(item))
        Integer contador = myMap.get(item);
        myMap.put(item, contador + 1);
        myMap.put(item, 1);

System.debug('$$$$$$$$$ myMap: Size: ' + myMap.size() + ' ; ' + myMap);

It prints the following:

$$$$$$$$$ myMap: Size: 2 ; {key1=2, key2=1}

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.