7

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?

8

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) – Sam Kamensky Aug 16 '16 at 17:10
  • 1
    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); – Sam Kamensky Aug 16 '16 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 Dec 10 '19 at 14:39

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.