In looping through a result set I fill a map with objects. Once the loop is completed though, there is a condition which requires me to update 1 of the values in the first instance of the map. How do I do this?

In a list it's easy:

list[0].field = 'abc';

How do I do this for a map?

1 Answer 1


if you have the key for the first element, you can simply do

YourMap.get(Key).field = newValue;

if you don't have the key for the first element, then you can try

List<Id> mapKeys = new List<Id>(yourMap.keySet());
YourMap.get(mapKeys[0]).field = newValue;
  • Hm, actually I'm getting an error of 'Expression cannot be assigned' with my sobjectmap (tried casting to the appropriate object which didn't fix it) Commented Aug 16, 2016 at 17:10
  • 3
    What worked for me was overwriting the value by using the map put method with the key. This also retains the order of the map set and values. You can test it with the code below Map<String,String> mapOrderTest = new Map<String,String>(); mapOrderTest.put('1','a'); mapOrderTest.put('2','b'); mapOrderTest.put('3','c'); mapOrderTest.put('4','d'); System.debug('Value of mapOrderTest prevalueUpdate: ' + mapOrderTest); mapOrderTest.put('2','Beta'); System.debug('Value of mapOrderTest postValueUpdate: ' + mapOrderTest); Commented Aug 16, 2016 at 17:17
  • @SamKamensky changing one item inside a record (while leaving the rest of the record as-is) in a map to an object data type requires more complex syntax than changing the single value in a map to a primitive data type.
    – Foo Bar
    Commented Dec 10, 2019 at 14:39

You must log in to answer this question.

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