Skip to content

Dave Helgerson

Salesforce Software Development and Consulting

Menu
  • Contact
  • Resume
Menu

Code Snipits for Converting Salesforce Collections

September 8, 2013October 16, 2013

Convert a Map to a List of keys

Map MyMap = new Map();
List IdList = new List();
// ... logic to load map ...
IdList.addAll(MyMap.keySet());

Convert a Map Values to a List of values

Map MyMap = new Map();
List CustomObjectList = new List();
// ... logic to load map ...
CustomObjectList.addAll(MyMap.values());

Convert an sObject List to a Map – Example 1 – New map with the List passed into the map’s constructor

Use this method when the map’s key value is the object’s Id. Thanks to this post for explaining the concept: King Koo

List MyList = new List();
// ... logic to load list ...
Map MyMap = new Map(MyList);

Convert an sObject List to a Map – Example 2 – Loop and Add

Use this method when the map’s key must be a field that is not an object’s id. This is useful when you need to find an object with a name instead of an Id value.

List MyList = new List();
Map MyMap = new Map();
// ... logic to load list ...
for(CustomObject__c c : MyList) {
  MyMap.put(c.Name, c);
}

Related

1 thought on “Code Snipits for Converting Salesforce Collections”

  1. Sattibabu says:
    October 29, 2016 at 2:32 pm

    Wonderful Dave. Seems simple blog but very informative on Maps. Thanks for sharing.

Comments are closed.

Super Clone Pro
© 2023 Dave Helgerson | Powered by Minimalist Blog WordPress Theme