LWC

Collections in Salesforce : How and when to use them – Explained with Examples

Collections is a relatively easy topic to understand but sometimes it may be a bit difficult to choose the best type of collection for a particular use case (especially as a beginning developer).

Read on to understand not just the basics but some useful problems that can be solved by collections, and get some analogies to get your creative ideas flowing. Especially the Maps section which explains in detail how to think of using them

Set

A set is an Unordered collection of Similar, Unique items. Pretty straightforward. Sure I get that.

But when would you use it?

To remove duplicates :

In the below example, even if you add a duplicate value in a set it will still only maintain unique values

public void exploringSets(){
    // Just created a set with some integers
    Set<Integer> setNum = new Set<Integer>{1,2,3,4};

    system.debug('Initial Set Contents: ' + setNum);
    //Try adding a duplicate value
    setNum.add(1);

    system.debug('Set Contents after duplicate value: ' + setNum);

}

Filter Record Ids by Criteria

It's a classic use case and a pattern which very common:

  1. filter out records based on a criteria
  2. Store the record Ids in a Set
  3. Use that set to query related records

public List filterOpportunityIdsWithAmount(List opportunities, Integer amount){

        Set filteredOpportunities = new Set();

// 1. Loop over a List and filter based on criteria
        for(Opportunity o : opportunities){
            if(o.Amount > amount){
//2. Store them in a set
                filteredOpportunities.add(o.Id);
            } 
        }
 // 3. Use the set to retrieve related records
        return [select id, Name, ListPrice from OpportunityLineItem where opportunityId in : filteredOpportunities];
    }
    

List

It is an Ordered Collection of Similar Items. Think of a shopping basket or a list of opportunities.

The important thing is since they are ordered you can reference the item by providing an index number

They really have a very broad set of applications

  1. Storing records in memory during transactions
  2. Bulkifying for DML operations
  3. Sorting, Lists have inbuilt methods for sorting
  4. Modifying records by looping over them and many more
public void exploringLists(){

    List accountList = new List();
    accountList = [select id, name from account limit 10];
        for(Account a : accountList){
            //Do what ever transformation you need
        }        
        update accountList;

    }

Map

It is a pretty interesting Data structure. And it can be thought of as KEY - Value pair in its basic form. But I like to think of it like a book.

So a book has page numbers that are unique and then on each page there can be content.

In the same, a map has a KEY that has to be unique and the data associated with it.

Let me demonstrate here,

public void exploringLists(){

    List accountList = new List();
    accountList = [select id, name from account limit 10];
        for(Account a : accountList){
            //Do what ever transformation you need
        }        
        update accountList;

    }


Great, but where do we really use them?

Building crosswalks

So from the previous example, we get a map/table looking like this

It is just a table of unique keys and some data, in this case just a string of student names.

So imagine we have an opportunity that has a custom field called studentID and we look to look at all such opportunities and and modify its name in the format of

A crosswalk table like the one you see here is exactly what we need.

This can also be written as

String studentName = StudentMap.get(opp.studentID__c);

Next, we take the name and insert the Opportunity with the format we need

opp.name = StudentMap.get(opp.studentID__c);
update opp;

Let’s get real:

You might have started to get the hang of it, but it's still a bit difficult to imagine without a real-life use case. So here’s one

A business process change prompted you to modify a picklist on a very large number of opportunities.

City Zone
New York East
Chicago Central
Austin Central
San Fransciso West

Now this can be done very easily by using the map

//populate the map:
Map cityToZoneMap = new Map();
cityToZoneMap.put('New York', 'East');
cityToZoneMap.put('Chicago', 'Central');

//So on and so forth

//Use the get method with the correct account city value
String accZone =  cityToZoneMap.get(acc.City);

Nesting Maps

You can Nest maps as well, for example: please forgive my unimaginative use of map names but they are only to show you what is possible

Map baseMap = new Map();

Map> nestedMap = new Map>();

Map>> nest2Map = new  Map>>();

There are a lot of analogies to understanding Maps, but I particularly prefer the book analogy here why

A book has many pages, a page has many lines, a line has many words and a word has many letters.

basically, with the right setup, you can create such a data structure

Representing a book with a map

Map&lt;Page, Map&lt;Sentences, Map&lt;Words, List&lt;Charaters&gt;&gt;&gt;&gt; bookMap = new Map&lt;Page, Map&lt;Sentences, Map&lt;Words, List&lt;Charaters&gt;&gt;&gt;&gt;()

Word of caution:

Just because you can create such a nested structure, really doesn't mean that you should. It becomes increasingly difficult to fetch data and populate such a Map. So, the example I gave here is just to demonstrate a point so please use your judgment.

Hope you are starting to get the picture of how you can use these structures for your use cases. Let me know in the comments if you want me to elaborate on anything in particular and I can try to make a follow-up post.

As always, keep coding and be awesome!!

Leave a Reply

Your email address will not be published. Required fields are marked *