Salesforce Data collections List ,Set ,Map
In Salesforce Apex, data collections such as lists, sets, and maps are used to store and manipulate data. These collections offer different functionalities and are suited for different use cases. Here's an overview of each:
A list is an ordered collection of elements where each element has an index.
Lists allow duplicate elements.
Elements in a list can be accessed using their index.
Lists are represented by the List class in Apex.
Example:
List<String> names = new List<String>();
names.add('Alice');
names.add('Bob');
names.add('Alice'); // Adding duplicate element
System.debug(names); // Output: (Alice, Bob, Alice)
Set:
A set is an unordered collection of unique elements. It does not allow duplicate elements.
Sets are useful when you need to ensure uniqueness and don't require the elements to be in a specific order.
Sets are represented by the Set class in Apex.
Example:
Set<String> uniqueNames = new Set<String>();
uniqueNames.add('Alice');
uniqueNames.add('Bob');
uniqueNames.add('Alice'); // Attempt to add duplicate element
System.debug(uniqueNames); // Output: (Alice, Bob)
Map:
A map is a collection of key-value pairs where each key is associated with a value.
Maps do not allow duplicate keys, but they can have duplicate values.
Maps provide efficient access to values based on their keys.
Maps are represented by the Map class in Apex.
Example:
Map<String, Integer> ageMap = new Map<String, Integer>();
ageMap.put('Alice', 30);
ageMap.put('Bob', 35);
System.debug(ageMap.get('Alice')); // Output: 30
Choosing the Right Collection:
Use lists when you need to maintain the order of elements and allow duplicates.
Use sets when you need to ensure uniqueness or perform set operations like union, intersection, etc.
Use maps when you need to associate values with keys or perform key-based lookups.
Iteration:
You can iterate over lists, sets, and maps using loops like for or for-each.
// Iterating over a list
List<String> names = new List<String>{'Alice', 'Bob'};
for (String name : names) {
System.debug(name);
}
// Iterating over a set
Set<String> uniqueNames = new Set<String>{'Alice', 'Bob'};
for (String name : uniqueNames) {
System.debug(name);
}
// Iterating over a map
Map<String, Integer> ageMap = new Map<String, Integer>{'Alice' => 30, 'Bob' => 35};
for (String name : ageMap.keySet()) {
System.debug(name + ': ' + ageMap.get(name));
}
Comments
Post a Comment