
Salesforce Apex Tutorial Chapter 11: Apex Collections

A collection is a type of variable in apex that can store multiple items.Collections In Apex can be List, Set, or Map.
- Lists
A list is an ordered collection of elements characterized by their indexes. A list element can be of any type, including primitive types, collections, sObjects, user-defined types, and Apex types. List in apex is similar to the array in Java. Each list index begins with 0. The list can store duplicate and null values.
Following are the methods supported by List.
- Add()
- Remove()
- clear()
- clone()
- Size()
- equals()
Example:
// Create an empty list of String
List<String> mylist = new List<String>();
mylist.add(‘Test1’);
mylist .add(‘Test2’);
mylist .remove(1);
- Sets
Sets are a collection of unordered elements that are not duplicated. There are several types of elements in the set — primitives, collections, sObjects, user-defined types, and built-in Apex types.
Following are the methods supported by sets:
- Add()
- Remove()
- Size()
- Contain()
- equals()
Example:
Set<Integer> mySet = new Set<Integer>();
mySet.add(1);
mySet.add(3);
System.assert(mySet.contains(1));
mySet.remove(1);
- Maps
The map is a combination of key-value pairs in which the key is unique and value can be multiple, Each unique key is mapped with a single value. A key and value can be of any data type, such as primitive types, collections of objects, user-defined types, or built-in Apex types.
Following are the methods supported by Maps in Apex:
- clear()
- clone()
- containsKey(key)
- deepClone()
- equals(map2)
- get(key)
- getSObjectType()
- isEmpty()
- keySet()
- put(key, value)
- putAll(fromMap)
- putAll(sobjectArray).
- remove(key)
- size()
- values()
Example:
Map<Integer, String> m = new Map<Integer, String>(); // Define a new map
m.put(1, 'First entry'); // Insert a new key-value pair in the map
m.put(2, 'Second entry'); // Insert a new key-value pair in the map
System.assert(m.containsKey(1)); // Assert that the map contains a key
String value = m.get(2); // Retrieve a value, given a particular key
System.assertEquals('Second entry', value);
Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map