Update records using map values

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.


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();
myList.add('key1');
myList.add('key1');
myList.add('key2');

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

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

It prints the following:

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