Apex has the following types of collections:
S.No | Collection Name | Description | Example |
1 | List | Ordered collection of typed primitives, sObjects, objects, or collections that are distinguished by their indices
| // Create an empty list of String List<String> my_list = new List<String>(); My_list.add(‘hi’); String x = my_list.get(0); // Create list of records from a query List<Account> accs = [SELECT Id, Name FROM Account LIMIT 1000]; |
2 | Map | Collection of key-value pairs where each unique key maps to a single value. Keys can be any primitive data type, while values can be a primitive, sObject, collection type, or an object. | Map<String, String> mys = new Map<String, String>(); Map<String, String> mys = new Map<String, String>{‘a’ => ‘b’, ‘c’ => ‘d’. toUpperCase()}; Account myAcct = new Account(); Map<Integer, Account> m = new Map<Integer, Account>(); m.put(1, myAcct); |
3 | Set | Unordered collection that doesn’t contain any duplicate elements. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types | Set<Integer> s = new Set<Integer>(); s.add(12); s.add(12); System.assert(s.size()==1); s.remove(1) //Remove the element from the set |
Note: There is no limit on the number of items a collection can hold. However, there is a general limit on heap size.
Total heap size is 6 MB.