Collections in Apex: List, Maps and Sets

6:18 PM

This post explains the differences between the different collections that are available in Salesforce Apex.

LIST:

A list is an ordered collection. A ordered collection is one where each element in the collection is stored in a specific position, and you could access the element using its position.


List<Integer> MyList = new List<Integer>();
MyList.add(10);
MyList.add(80);
MyList.add(50);
MyList.add(30);
MyList.add(10); //Duplicate entry

  • List can have duplicate entries. The integer 10 is added twice to the list.
  • List is a ordered collection, meaning that each element is stored in a specific position. An element can be accessed using its location (also called as Index). The index always starts with 0.
List can also contain SObject records, here is a sample code. Note that removing/adding a record to the list does not add it to the database. You should explicitly use the DML commands insert/upsert/delete.

List<Account> listsample = [Select Id,Name from Account limit 5];
system.debug('The Account Name at index 0 is'+listsample[0].Name);
system.debug('The size of the list is'+listsample.size());
//Adding a element to the list
listsample.add(new Account(Name='testlistsample'));
system.debug('The size of the list now is'+listsample.size());
//Remove a element from the list
listsample.remove(5);
system.debug('The size of the list now is'+listsample.size());

SET:

A set is an unordered collection. Elements in a set are not stored in a specific order and you cannot access an element using an index.

Here is a sample code:

Set<String> Accountids = new Set<String>();
for (Account a: [Select Id from Account limit 5])
    Accountids.add(a.Id);
system.debug('The size of the set is'+accountids.size());
for (Account a: [Select Id from Account limit 5])
    Accountids.add(a.Id);
system.debug('The size of the set is'+accountids.size());



MAPS:

A Map is a collection of Key Value pairs. Each key corresponds to an element. Below is a diagram which illustrates this.


A major difference between a Map and a List is traversal. In a List you will have to loop through each element to find out a specific element, whereas in a map you could fetch it directly using the key. This greatly reduces processing time.

Map<Id,Account> testmap = new Map<Id,Account>([Select Id,Name from Account limit 5]);
system.debug('The size of the map is'+testmap.size());
system.debug('The keys are'+testmap.keySet());
system.debug('The values are'+testmap.values());



1 comments

  1. we can use the index to get to specific element in list.
    can u please eloborate your explanation on diff between list,map.
    also tel me diff between set , map

    ReplyDelete