Collections in Apex: Lists, Sets, and Maps

Collections in Apex: Lists, Sets, and Maps – Tutorial 4

Spread the love

In Apex programming, collections are like containers that help you store and manage multiple pieces of data. They’re like the different types of boxes you might use to organize your belongings. The three main types of collections in Apex are Lists, Sets, and Maps, and each has its own unique characteristics and use cases.

Lists

Think of a List in Apex as a simple ordered container, much like a to-do list. You can add items to a List, and they maintain their order. It’s like writing tasks on sticky notes and putting them in a line. Lists are useful when you want to work with a collection of items and need to keep them in a specific sequence.

List<String> shoppingList = new List<String>();
shoppingList.add('Apples');
shoppingList.add('Bananas');
shoppingList.add('Milk');

Sets

Sets are a bit different. They are like a collection of unique keys, just like a set of keys you might have for different doors. Sets automatically remove duplicate values, so you won’t have the same item more than once. They are great for maintaining a list of unique elements.

Set<String> uniqueNames = new Set<String>();
uniqueNames.add('John');
uniqueNames.add('Alice');
uniqueNames.add('John'); // Won't be added again, as it's a duplicate.

Maps

Maps are like dictionaries where you have a key and a value associated with it. Think of it as a phone book where a name (the key) corresponds to a phone number (the value). Maps are used to store and quickly retrieve data based on a unique identifier.

Map<String, Integer> ageMap = new Map<String, Integer>();
ageMap.put('John', 30);
ageMap.put('Alice', 25);

Collections in Apex are incredibly handy when you need to work with multiple pieces of data together. Lists maintain order, Sets ensure uniqueness, and Maps allow for efficient data retrieval. Choosing the right type of collection depends on your specific needs in your Apex code. These collection types help you organize and manipulate data efficiently, making them valuable tools in Salesforce development. As you become more proficient in Apex, you’ll find yourself using collections frequently to handle complex data scenarios in your applications.


0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Open Chat
1
Dear Sir/Madam
How can I help you?