How do I update a value IN a map?

  • 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?

  • 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)

    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 mapOrderTest = new Map(); 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);`

    @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.

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used