Collections in Salesforce

Learn All About Collections in Salesforce: List, Set and Map

In this Blog, we will study collections in Salesforce.

List 

It is an ordered collection of elements. Each element of the list has a unique index and the index of the first element of the list always starts with 0. 

The list can be nested and multi-dimensional. 

List elements can be a primitive, collection, sObject, User-defined types, and built-in types. 

Example:

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

List Methods

  • To add records in list - mylist.add(‘a’); 
  • To get a particular index value Integer i = mylist.get(0); 
  • To add value at any particular index – mylist.add(1,30); 
  • To clean or clear list – mylist.clear(); 
  • To check the size of the list – Integer s = mylist.size(); 
  • To check the list is empty or not – Boolean b = mylist.isEmpty(); 
  • To add values of a list into another list – mylist.addAll(fromList); 
  • To add values from a set into list – mylist.addAll(fromSet); 
  • To clone a list – mylist.clone(); 
  • To check if a value is available inside the list – mylist.contains(‘value’); (This returns a boolean value). 
  • To compare two lists – mylist.equals(list2); 

System.debug(‘List Contains...’ + mylist); 

dont miss out iconDon't forget to check out: Mastering Apex Collections | Salesforce Tutorial

Set 

An unordered collection of elements and it does not contain duplicate elements. 

It can be nested and elements of a set can be – primitive, collection, sObject, user-defined type and built-in type. 

Example:

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

Set Methods

  • To remove from set – myset.remove(20); 
  • To check if set is empty – isEmpty(); 
  • To retain set elements – retainAll(setofElementsToRetain); 

Map 

A map is a collection of key-value pairs. Keys are always unique whereas values can be duplicated. In apex, we use the hash structure for all maps. Map key and value can be nested and can contain any collection such as primitive type, collection, sObject, user-defined types, and built-in type. 

Example:

Map<String, String> mymap = new Map<String, String>(); 

Map Methods

  • To add value in map – mymap.put(1,’First’); 
  • To copy all mapping from specified to original map – putAll(fromMap); 
  • To remove the mapping of the specified key – remove(key); 
  • To return the number of key-value pair in map – size(); 
  • To return a list that contains all the values of the map – values(); 

dont miss out iconCheck out another amazing blog by Bhawana here: What are Apex Basics? A Guide in 2023

Enum 

Enum is an abstract data type and it is used to define a set of possible values. 

Example:

public enum Weekdays{Mon, Tue, Wed, Thu, Fri, Sat, Sun} 

Weekdays w = Weekdays.Mon; 

if(w == Weekdays.Tue) 

return w; 

This is all about Collections in Apex. I hope this information is helpful to you. 

Responses

Popular Salesforce Blogs