Collections in Apex (List, Set, Maps)

Welcome to learnsalesforce.co, in this Salesforce tutorial you will learn the different types of collections in Apex, how collections are related to each other, how to define each collection and when we use collections in Apex. In every programming language, there are collections. The collection could be considered as a type of variable that can store multiple records. For example, a List is a collection, which can store several Account object’s records. The list is not only a collection variable in Apex programming language, but it is also there in the other programming languages as well. In this chapter, we will discuss collections in Apex.

Lists

A list in Apex is analogous to an array in other programming languages that is it is an ordered list of items that can be referenced by their index. Lists can contain any data type, but they must have a defined data type. We declare a list in a similar way to declaring a new sObject.

List<datatype> myList = new List<datatype>();

We use list keyword and include the datatype for the list in angular brackets <> afterward. We then continue our variable definition with the variable name and the equals sign, before the new keyword and the List<datatype> definition again, followed by a pair of parentheses ( ) to create the new list instance.

Example:-

List<String> names = new 
List<String>(); 
List<Integer> ages = new List<Integer>(); 
List<Account> accounts = new List<Account>();
List<Job__c> jobs = new List<Job__c>(); 
List<List<Integer>> grid = new List<List<Integer>>();

The list is capable of holding any number of records of the following type.

  • Primitive
  • Collections
  • sObjects
  • User-defined types
  • Built-in Apex type.

This is considered the most important type of collection in Apex. Apex has some system methods which have been created specifically to use with List. The list index always starts with 0. This is similar to the array in Java. A list should be declared with the keyword ‘List’.

Apex supports multiple methods that can be used for programming with List. Some of these methods are listed below.

  • size()
  • add()
  • get()
  • clear()
  • set()

Set

A set is an unordered collection of unique items. Unlike lists, sets are collections of unique elements with no duplicates. A Set is a collection type in Apex, that contains multiple numbers of unordered unique records. One of the unique features of Set is, it cannot have duplicate records. Like Lists, Sets can be nested as well. You declare a set using the Set keyword in a way very similar to that of declaring a list: 

Set<String> myStringSet = new Set<String>(); 

And again we can initialize with some values if they are known using the curly bracket notation and add items using the add() method: 

Set<String> compassSet = new Set<String>{'North', 'South'}; 
compassSet.add('East'); 
compassSet.add('West');

Sets do not allow the storing of duplicates, so if we tweaked our earlier code to use a Set instead: 

Set<String> compassSet = new Set<String>(); 
compassSet.add('North'); 
compassSet.add('South'); 
compassSet.add('East');
compassSet.add('South');
compassSet.add('West');
compassSet.add('West');

The size of the set would remain at 4, ‘North’, ‘South’, ‘East’, ‘West’ as those are the only unique values. Another difference between sets and lists is that you cannot access elements in a set using an index. When working with sets, it is usually to create a unique collection of elements for use in a filter for a query. You can check to see if the set contains a specific element using the contains method that returns a Boolean value:

Set<String> names = new Set<String>{'Paul', 'Amanda'}; 
Boolean hasPaul = names.contains('Paul'); //true
Boolean hasAmanda = names.contains('Amanda'); //true
Boolean hasSophie = names.contains('Sophie'); //false

It is also common to compare whether a set contains another list or set:

Set<String> names = new Set<String>{'Eddie', 'Penny', 'Lila'}; 
Set<String> names1 = new Set<String>{'Eddie', 'Penny'};
List<String> names2 = new List<String>{'Lila', 'Penny', 'Suzie'};
names.containsAll(names1); //true

Maps

Maps are a collection of key-value pairs that allow us to store a variety of data types using a key of any data type rather than an integer as an index. A map is a key-value pair that contains the unique key for each value. Both keys and values can be of any data type.

We declare a map using the Map keyword and placing 2 parameters into the angular brackets rather than a single parameter as we would for a List or a Set. The first is the data type of the keys and the second the data type for the values:

Map<keyType, valueType> mapName = new Map<keyType, valueType>();

We can use any data type for both the keys and the values. For our example above where we wanted to create a map where we used the name of the account as the key and the number of employees for an account as a value, we would define this map as follows:

Map<String, Integer> employeesByAccName = new Map<String, Integer>();

To add values to a map you use the put method which takes in 2 parameters, the key-value you wish to populate and the value you wish to associate with that key: 

employeesByAccName.put('Acme', 1000); 
employeesByAccName.put('Brix', 550);

This code associates the value 1000 with the key Acme and the value 550 with the key Brix. To retrieve the value for a key from the map we then use the get method for the map which takes in the key-value as a single parameter and returns the value from the map if it exists, and returns null other wise.

Integer acmeEmployees = employeesByAccName.get('Acme');//1000 
Integer brixEmployees = employeesByAccName.get('Brix'); //500 Integer testEmployees = employeesByAccName.get('Test'); //null

Map values are unordered and as a programmer, one should not rely on the order in which the values are stored. We should rather try to access the map always using keys. The map value can be null. Map keys when declared String are case-sensitive.

Conclusion

In this Salesforce tutorial, we have learned what are the three different types of collection in Apex are and how we can instantiate and use them.