Create Collections in APEX and initiate them

A cheat-sheet for the Salesforce developer

Posted by Martin Haagen on Wednesday, April 5, 2023

Create Collections in APEX and initiate them

As a developer of multiple languages, I must remember how to create the different collection types when writing code in APEX. Sure, it is simple enough to make an empty collection, but you often want to create and initialize it simultaneously. This is when my memory struggles to remember.

You may be the same - and here is a small cheat sheet that will help you in these situations.

The List Collection Type

A list is an ordered collection type where the items do not need to be unique.

To create a new empty list, declare it with its datatype in the following manner.

List<String> stringList = new List<String>();

Often you would want to create a list and initiate it with data; this could be from a typed list, or the result returned from a SOQL query.

List<String> stringList = new List<String>{
  ‘firstString’,
  ‘secondString’
};
List<Account> accountList = [SELECT Id, Name FROM Account];

As you will notice, curly brackets will be the way to initialize any collection object with typed values.

The Set Collection Type

A set is similar to a list but with one significant difference; it will only contain unique values. Therefore, if you add the same values multiple times, the system will ignore the duplicate values.

You create an empty set by declaring it with its data type like this.

Set<Id> opportunitySet = new Set<Id>();

In most languages, it follows the expected pattern for creating any collection type. So, for example, if you want to create a set with a typed list of values, you can similarly do that as you would do with lists.

Set<String> stringSet = new Set<String>{
  ‘firstString’,
  ‘secondString’
};

As you see, curly brackets are the way to do this.

The Map Collection Type

A map is a beneficial collection type that differs slightly from the list and set collection types. It is a key/value store. The collection type is even more helpful since you can access all the keys as a set and all the values as a list.

To create the empty map, you would do just as expected.

Map<Integer, String> stringMap = new Map<Id, String>();

If you want to create a map with typed keys and values, you can do that in the following manner.

Map<Integer, String> stringMap = new Map<Integer>{
  1 => ‘firstString’,
  2 => ‘secondString’
};

I like maps because you can create and load them with data using a SOQL query - super helpful when referencing or linking data from different sources.

Map<Id, Opportunity> oppMap = new Map<Id, Opportunity> (
  [SELECT Id, Name FROM Opportunity]
);

These examples will help you remember how to initiate these powerful objects when needed. If you need more information about collection methods, you can find it the APEX Developer Guide