Wednesday, 29 August 2012

Sets and Maps - Apex Language Fundamentals

Besides Lists, Apex supports two other collection types: Sets and Maps.

Sets

A set is an unordered collection of objects that doesn’t contain any duplicate values. Use a set when you don’t need to keep track of the order of the elements in the collection, and when the elements are unique and don’t have to be sorted.
The following example creates and initializes a new set, adds an element, and checks if the set contains the string 'b': You can run this example in the Developer Console.
Set<String> s = new Set<String>{'a','b','c'};
// Because c is already a member, nothing will happen. 
    
s.add('c');
s.add('d');
if (s.contains('b')) {
    System.debug ('I contain b and have size ' + s.size());
}
After running the example, you will see this line in the output:.

Output of the Set contains method.

Maps

Maps are collections of key-value pairs, where the keys are of primitive data types. Use a map when you want to store values that are to be referenced through a key. For example, using a map you can store a list of addresses that correspond to employee IDs. This example shows how to create a map, add items to it, and then retrieve one item based on an employee ID, which is the key. The retrieved address is written to the debug output.
Map<Integer,String> employeeAddresses = new Map<Integer,String>();
employeeAddresses.put (1, '123 Sunny Drive, San Francisco, CA');
employeeAddresses.put (2, '456 Dark Drive, San Francisco, CA');
System.debug('Address for employeeID 2: ' + employeeAddresses.get(2));
After running the example, you will see this line in the output:.

Output of the Map value corresponding to key value 2.
Maps also support a shortcut syntax for populating the collection when creating it. The following example creates a map with two key-value pairs. If you execute it, the string ‘apple’ will be displayed in the debug output.
Map<String,String> myStrings =
new Map<String,String>{'a'=>'apple','b'=>'bee'};
System.debug(myStrings.get('a'));
Sets and maps contain many useful methods. For example, you can add all elements of one set to another using the addAll method on a set. Also, you can return the list of values in a map by calling values.

No comments:

Post a Comment