function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion

Map Values carrying over out of order

Hello everyone, I'm tryng to make it so that my pdf controller can build by product subcategory, without the need to hardcode it in.


To do this, I performed a mix of Custom Object and Map<String, List<LineItems>> in my controller, and for the most part it works, except when transferring the values of the Map to a List<List<LineItems>>, it becomes out of order and products will be put under the wrong category. Any idea how I can address this issue?


Thank you for your time.


Maps are unordered collections.  


Thus for each entry in the map, the List<lineItems> will retain the order that you created them in (because it is a List, which is an ordered collection).  However, if you extract the values, these will not be in the order that you added them to the map.


From the apex docs for the values method (highlighting mine):



Returns a list that contains all of the values in the map in arbitrary order.



What do you recommend I do then?


As you can't do anything to alter the behaviour of a map, you'll need to store your data in an ordered collection.  Is it possible to change your data structure so that you use a list rather than an map?


If not, you'll need a list that mirrors the map, and every time you add an element to the map you'll also add it to the mirroring list.   If you need the key and the matching list, you'll need a custom object that encapsulates both of these, and you can then create a list of those.





public class Combo
   public String key;
   public List<LineItem> lineItems;

   public Combo(String inKey, List<LineItem> inLineItems)

Map<String, List<LineItem>> myMap;
List<Combo> mirrorList;


// adding to list
List<LineItem> newList=new List<LineItem>();
String key='test';
myMap.put(key, newList);
mirrorList.add(new Combo(key, newList);



So mirrorList contains everything that the map contains, but in the order that you added them to the map.