How to use Collections in Salesforce Apex

on

|

views

and

comments

Table of Contents

Introduction

A collection is a data structure(Data Types) that is used to store multiple values of the same data type. Collections are used to manipulate large sets of data efficiently and effectively.

If we have to store multiple values of the same type then if we do not use collection. Then here is how we will store the variables

String name;
String name1;
String name2;
String name3;
..
..
..
..
..
..
String nameN;

String fruit = ‘Apple’;
String fruitName = ‘Banana’;

Types of Collection

There are mainly three types of collection in Salesforce

  • List
  • Set
  • Map

List Collection in Salesforce

A list is a collection of elements that are ordered and can be accessed using their index. The elements of a list can be of any data type, including primitive and non-primitive data types.

In Salesforce, lists are represented by the “List” keyword in Apex code and are commonly used to store and manipulate large data sets.

There is a class named List.

List<Data Type> variabname = new List<Data Type>();

Lists allow for various operations such as adding or removing elements, iterating over elements, searching for elements, and sorting elements.

List of Index = Total Size of List(Total Elements in List) – 1
Total Index = 4
First Index = 0
Last Index = 4-1

Hands-On

				
					// Syntax
#1 -
List<Data Type> variabname = new List<Data Type>();

// Declare & Memory Allocation
List<String> fruitList = new List<String>(); // Size = 0, Size = 1

// Declare & Memory Allocation & Value Assignment
#2 - 
List<String> fruitList = new List<String>{'apple', 'banana', 'orange'};

List<String> orderStatusList = new List<String>{
    'Created','Submit','In Process',
    'Out for Delivery','Delivered',
    'Return Requested','Return Pickup Scheduled',
    'Retured', 'Refund Requested', 
    'Refunded'
};

List<Integer> numbersList = new List<Integer>{1,2,4,5,3};

// Declare the variable
#3 -
List<String> fruitList; // null

fruitList = new List<String>(); // Memory Allocation

fruitList = new List<String>{'apple', 'banana', 'orange'}; // Memory Allocation & Value Assignment

fruitList1 = new List<String>{'apple', 'banana', 'orange'};


				
			

Methods of List in Salesforce

There are numerous methods of List class in Salesforce, however, there are some that are being used widely by the developers

#1- 
List<Data Type> variabname = new List<Data Type>();
  • add(element)
  • set(index, element) – 1, ‘banana’
  • get(index) – 0, 1, 2
  • clear()
  • clone()
  • addAll(another set or list)
  • remove(index)
  • isEmpty()
  • size()
  • sort()
  • Etc

For more information refer to this link – https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm

When to Use List

  • Ordering the element is important
  • Need of accessing the element by indexes
  • Sorting is important
  • Need to create records inside Salesforce sObjects
  • Need to store the records from the SOQL Queries
  • You need to store multiple dimensions like Matrix

Hands-On

				
					// List<Data Type> variabname = new List<Data Type>();
List<Integer> numbers = new List<Integer>{4,5,6,6,6,6};
System.debug(' numbers '+ numbers);
List<String> frtuits = new List<String>(); // heap memory
frtuits.add('Grapes'); //0
frtuits.add('Mango'); //1
frtuits.add('Apple');//2
frtuits.add('Grapes');//3
frtuits.add('Banana');//4
// Size - 5
// Start Index = 0, Last Index = size - 1 = 4
System.debug(' frtuits '+ frtuits);
frtuits.set(1, 'Guava');
System.debug(' frtuits after set method '+ frtuits);
System.debug(' Index 2 '+ frtuits.get(5) ); 
String abc = frtuits.get(2);
Integer xyz = numbers.get(2); // String
//Illegal assignment from String (Right side after =) to Integer(left side before =)
Integer length = frtuits.size();
Boolean isEmpty = frtuits.isEmpty();
System.debug( length );
// 6MB - Sync , 12MB - Async
frtuits.clear();
System.debug( frtuits );
System.debug( frtuits.get(2) );
if(frtuits.isEmpty() == false){
    System.debug(' List is Not Blank ');
}else{
    System.debug(' List is Blank ');
}
				
			

Set in Salesforce

→ Set is an unordered set of collections elements.
→ Set does not contain the duplicate element
→ You can not access elements using indices
→ Below is visual representations of a set of String

Syntax of Set

				
					Set<Integer> colorsSet = new Set<Integer>();
Set<Integer> colorsSet = new Set<Integer>{'Red', 'Black', 'Blue', 'Green'};
Set<Integer> colorsSet;
				
			

Methods of Set in Salesforce

There are numerous methods of Set in Salesforce, however, there are some that are being used widely by developers.

  • add(element)
  • contains(element)
  • addAll(another set or list)
  • clear()
  • remove(value)
  • size()
  • isEmpty()
  • Ect

For more information refer to this link – https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_set.htm

When to Use Set

  • Ordering is Not Important
  • To Store the recordIds or Unique Elements like Emails, Phone

Hands-On

				
					Set<String> colorsSet = new Set<String>{'black','Red', 'Black', 'Blue', 'Green','Black'};
System.debug(colorsSet);
System.debug(colorsSet.contains('Black') ) ;
Integer length = colorsSet.size();
Boolean isEmpty = colorsSet.isEmpty();
//colorsSet.clear();

Set<String> fruitsSet = new Set<String>();
fruitsSet.add('Apple');
fruitsSet.add('Banana');
fruitsSet.add('Mango');
colorsSet.addAll( fruitsSet );
System.debug(colorsSet);

Set<Integer> numberSet = new Set<Integer>{3,4,5,5,5};
colorsSet.addAll( numberSet );
				
			

Hands-On

				
					Set<String> colorsSet = new Set<String>{'black','Red', 'Black', 'Blue', 'Green','Black'};
System.debug(colorsSet + '\n ');
System.debug(colorsSet.contains('Black') ) ;
Integer length = colorsSet.size();
Boolean isEmpty = colorsSet.isEmpty();
colorsSet.clear();

Set<String> fruitsSet = new Set<String>();
fruitsSet.add('Apple');

Account accountRecord = new Account();
accountRecord.Name = 'SET ACCOUNT DEMO';

Account accountRecord1 = new Account();
accountRecord1.Name = 'SET ACCOUNT DEMO';

Account accountRecord2 = new Account();
accountRecord2.Name = 'SET ACCOUNT DEMO2';

Set<Account> accountSet = new Set<Account>();
accountSet.add(accountRecord);
accountSet.add(accountRecord1);
accountSet.add(accountRecord2);
System.debug(accountSet);

List<Account> accountList = new List<Account>();
// accountList.add();
accountList.addAll(accountSet); // Set<Account> // Account
System.debug(accountList);
insert accountList;
/*
global class List{
    global void addAll(List<Object> elements){
        for(Ineteger i=0; i< elements.length; i ++){
            accountList.add( elements[i] );
        }
    }
}
*/
				
			

Assignment

  1. Create a List to Store Some of the Salesforce Certifications
    1. Playaround with the methods
  2. Create a Set to store the Salesforce Certifications related to Salesforce Developers
    1. Playaround with the methods

https://trailhead.salesforce.com/en/credentials/administratoroverview/

Resources

Amit Singh
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to start your AI Journey?

Table of Contents Introduction Are you tired of the same old world? Do you dream of painting landscapes with your code, composing symphonies with data, or...

The Secret Weapon: Prompt Engineering: 🪄

Table of Contents Introduction Crafting the perfect prompt is like whispering secret instructions to your AI muse. But there's no one-size-fits-all approach! Exploring different types of...

How to Singup for your own Production org?

Let's see how we can have our salesforce enterprise Salesforce Org for a 30-day Trial and use it as a Production environment. With the...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential