0% found this document useful (0 votes)
14 views

Apex Basic Part - 3 Collections

Uploaded by

sujatha.it9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Apex Basic Part - 3 Collections

Uploaded by

sujatha.it9
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

TASK

Get 2 green balls, 1 blue ball, and 3 pink balls from


below. Which one should you choose, A or B?

B
Option B is likely to have a predetermined
arrangement or composition that allows you to easily
select the specific number and color of balls you
need.
100% Predictability

Ease of Selection

Precision

Searching Time

Option A, with a mixed arrangement, may not


guarantee the desired combination, making it more
challenging to obtain the required balls in the
specified quantities and colors

Searching Time

Effort to Search
DATA
Structure

A data structure is a way of organizing, storing,


and managing data to facilitate efficient access
and modification.
It defines the relationship between the data,
the operations that can be performed on the
data, and the rules for those operations.
There are two main types of data structures:
1. Primitive Data Structures
These are basic and fundamental data
structures.
Examples include integers, floating-point
numbers, characters, and Boolean values.
2. Composite Data Structures
These are built by combining primitive data
types and other composite types.
Examples include arrays, lists, stacks,
queues, trees, graphs, and hash tables.
In Apex, which is the programming language used in
the Salesforce platform, you can work with various
data structures to organize and manipulate data.
Some common data structures in Apex include

L I S T
List in Apex are ordered collections of
elements.
Elements in a list can be of any data type,
including other lists

how to create a list variable in apex ?


list<Integer> ListOfNumber = new List<Integer>();

This part initializes a new instance of


Collection<Datatype> the List<Integer> class. The ‘new‘
keyword is used to create a new
object, and List<Integer>() is the
constructor call for the List<Integer>
class in Apex.

After this code is executed, you have a variable named listOfNumber


that is a list capable of holding integer values in Apex.
how to store a value in the list?
list<Integer> ListOfNumber = new List<Integer>();
ListOfNumber.add(7);
ListOfNumber.add(2);
ListOfNumber.add(9); add method is specifically
system.debug(ListOfNumber); used to add elements to
the end of the list in Apex.
>> (7,2,9)

7 2 9

Memory
arrangement
xef001 xef002 xef003
Elements are stored in contiguous memory
locations, so Lists have the advantage of
easy access to values through index-based
retrieval

Note
In Apex, you cannot directly obtain the memory location
(address) of a variable like you might do in languages
such as C or C++.
Apex, being a high-level programming language,
abstracts low-level details like memory management to
provide a more secure and platform-independent
environment.
how to iterate a value in the list?
Using a Traditional For Loop

Using a For-Each Loop

Use a traditional for loop when you need explicit control over
the iteration, such as accessing or modifying the index, or
when you need to modify the collection during iteration.

for (Integer i=0; i<listOfNumbers.size(); i++)


{
Integer value = listOfNumbers.get(i);
System.debug(value);
}

U must Initialization for iterate the collection


U need to know the length of the list

Use a for-each loop for cleaner, more readable code when


you simply need to access each element in the collection and
do not need to modify the collection or access the index of
each element

for(Integer num : listOfNumbers) {


System.debug(num);
}
List<Integer> listOfNumbers = new List<Integer>{2,4,6,8,10};
for (Integer i = 0; i < listOfNumbers.size(); i++)
{
listOfNumbers[i]+=10 ;
}
system.debug(listOfNumbers);

>> (12,14,16,18,20) Support modify

for (Integer num : listOfNumbers) {


num+= 10 ;
} Readable
system.debug(listOfNumbers);

>> (2,4,6,8,10) Simple

Index vs size
Index In the context of arrays or lists, an index refers to
the position of an element within the data structure.
Indexing usually starts from 0 in programming
languages. For example, in the list [10, 20, 30], 10 is at
index 0, 20 is at index 1, and 30 is at index 2.
Size: Total number of elements it contain in list.

10 20 30 40 Size - 4

Index 0 1 2 3
how to clone a list?
List<Integer> StockList1 = new List<Integer>{2,4,6,8,10};
List<Integer> StockList2 = new List<Integer>();
StockList2 = StockList1;
StockList2.add(12);
system.debug(StockList1);

>> (2,4,6,8,10,12)
I add 12 in Stocklist2 but it
automatically add 12 in Stocklist1 also
How?
because both lists share the same memory StockList1 is
just a reference of the StockList2 is called shallow copy.
Example - Mirror

List<Integer> StockList1 = new List<Integer>{2,4,6,8,10};


List<Integer> StockList2 = new List<Integer>();
StockList2.addall(StockList1);
StockList2.add(12);
system.debug(StockList1);

>> (2,4,6,8,10)

For this using a built


function in list. Addall

Deep copy create a separate memory space for the new list
How to check whether the list is initialised or
not?
list <integer> IntStockList = new list<integer>();
system.debug(IntStockList);

>> ( ) 1
list <integer> IntStockList ;
system.debug(IntStockList);

>> Null 2

IntStockList.add(10);
System.NullPointerException: Attempt to de-reference a null
object
3

1) It return empty means that the intStockList variable has


been allocated memory space for a List<Integer> object, but
since no Integer values have been added to this list, it is
currently empty.
2) IntStockList is declared but not initialised. When you try
to debug it, it will output null because no memory has been
allocated for the list.
3) If you were to perform operations on this list without
initialising it first, you might encounter NullPointerExceptions
or other errors

Best Practies - Always ensures that List is not null, and you can
safely perform operations on it without worrying about null
references
Why List is important in apex ?

Data Retrieval - When querying records from


the Salesforce database, such as using SOQL
queries like [Select Name from Account], the
result is returned as a list of records. Lists
provide a structured way to hold and
manipulate this data within Apex

Bulkification -
Salesforce Governor Limits impose restrictions on
the number of records and operations that can be
performed in a single transaction.
Lists allow for bulk processing of records,
enabling developers to efficiently work with large
datasets while adhering to these limits.
Bulk processing involves performing operations
on collections of records rather than individual
ones, which helps in optimizing performance and
avoiding governor limit issues.

Data Manipulation -
Lists provide a convenient way to manipulate
and work with collections of data. Developers
can iterate over lists, filter records based on
specific criteria, sort records, and perform
various other operations to meet their business
requirements
S E T
Set is an unordered collection .It cannot allow duplicates.

List<integer> IntStockList = new List<integer>();


IntStockList.add(23);
IntStockList.add(20);
IntStockList.add(20);
system.debug(IntStockList); Allow Duplicate
>> (23, 20, 20)

Set<integer> IntStockset = new Set<integer>();


IntStockset.add(23);
IntStockset.add(20);
IntStockset.add(20);
system.debug(IntStockset );
>> {20, 23}
Donot Allow Duplicate

Can a set be accessed by index?

system.debug(IntStockList[0]);
Ordered
>> 23

system.debug(IntStockset[0]);

Expression must be a list type: Set<Integer>

It shows the proof of set is an


unordered collection.using index u
cannot access the values in the set.
Remove a value in Collections
System.debug(IntStockList.remove(0)); Remove by using index
>> 23
System.debug(IntStockList.size());
>> 2
System.debug(IntStockSet.remove(20));
>> True
System.debug(IntStockSet.size());
>> 1

Sets do not use indexes for removal,


you remove by value

Purpose of SET

List<Integer> StockList =
new List<Integer>{2,3,4,5,6,3,4,5};

Set<Integer> StockSet = new Set<Integer(StockList);

System.debug(StockSet);

The main purpose of converting a List


to a Set in many contexts, including
Apex programming, is indeed to
remove duplicates from the list
MAP

Words in a dictionary are typically arranged in alphabetical


order, which facilitates easy lookup and reference. Similarly,

Map collection is a key tool for developers. It's similar to


dictionaries in other programming languages like Python
or objects in JavaScript, where data is stored as key-value
pairs.
This structure is very efficient for quickly retrieving,
updating, or checking for the existence of values based on
their keys
A Map in Apex can hold any type of data as the key
(though it's commonly a String or an Id for Salesforce
record IDs) and can map to any type of data as the value.
This makes it incredibly versatile for various programming
needs, such as caching results, grouping records by a
specific field
Creating a Map in Apex

Declare a map variable


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

Map<String, Integer>:
This specifies the type of the map being declared. In
Apex, a map is a collection of key-value pairs where each
key maps to a single value.

system.debug(Courses);

>> {}
returns {} (an empty map) is because
you've just initialized Courses and
haven't added any key-value pairs to it
yet

Add a value in Courses Map


Courses.put(101,'JAVA'); If you want to add
Courses.put(102,'Python'); entries to the map you
Courses.put(103,'C++');
can use the put method
Course is a map that maps Integer keys to string
values. We add three key-value pairs to Courses:

Key Maps To Value

101 Java

102 Python

103 C++

why searching in a Map is faster compare to List ?

Key-Value Pair Structure:

Maps in Apex are implemented as key-value


pairs, where each key is associated with a
value.
When you search for a specific key in a Map,
Apex can directly access the corresponding
value in constant time (O(1)) because it uses
hashing to store and retrieve elements.
Hashing Algorithm: Maps internally use hashing
algorithms to determine the location of each key-
value pair. This allows for efficient storage and
retrieval of elements without needing to iterate
through the entire collection.

Indexed Access:
Since Maps are indexed by their keys,
accessing an element by its key is faster
compared to iterating through a List to find a
specific element.
Lists require linear search, which takes O(n)
time complexity on average, where n is the
number of elements in the List.

How to find a value in the map?


system.debug(Courses.get(101));
>>Java

Courses.get(101) is retrieving the


value associated with the key 101
from the Courses map
Key cannot be Duplicate ?

Courses.put(101,'JAVA');
Courses.put(102,'Python');
Courses.put(103,'C++');
courses.put(103,'Salesforce');

103 Salesforce

Note that when you put a new value with an existing key in a
map, it updates the value associated with that key, so the
value for the key 103 is updated from "C++" to "Salesforce".
Also, maps do not allow duplicate keys, so if you put a key
that already exists, it will simply update the associated value

system.debug(Courses.keyset());
>> {101, 102, 103}

Keyset returns all the keys present in


the map. It returns these keys as a set
because keys in a map are unique;
they cannot be duplicated
Contains key

if (Courses.containsKey(103)) {
system.debug(Courses.get(103));
}
else{
system.debug('key not available');
}
containsKey method is being used to
check if a specific key (103 in this
case) exists within the Courses
collection or not.

size
Integer size = Courses.size();
system.debug(size);

>> 3 Returns the number of key-value


mappings in the map.

You might also like