Collections
Summary
This post will cover topics below:
- Introduction
- Define and Initialise List, Set, and Map.
- Useful methods for List, Set, and Map.
- Examples for List, Set, and Map.
- Exercises
Introduction
Collections
Group of data/records with the same data type.
Type of collections
There are 3 types of collections in Apex. The types are:
- List
- Set
- Map
Headings
List
A Collection which allow duplicate value.
Variations to declare and initialise list:
List<Integer> collNumbers = new List(); // ()
List<Integer> collNumbers1 = new List<Integer>{1, 2, 3}; //(1, 2, 3)
List<Integer> collNumbers2 = new Integer[5]; //(null, null, ...)
List<Account> collAccounts = [SELECT Id, Name FROM Account]; //(Account:{Id=0012x000004SNHTAA4, Name=KenCorp}, ... );
Useful methods:
- .get(Integer index_param) : get element at param index
- add(param): insert data at the end of the list.
- sort(): sort the members of the list
- clear(): remove all elements in the list
- size(): get the length of the list
Example:
List<Integer> listNumbers = new List{1, 3}; //(1, 3)
//add member into list
listNumbers.add(2); // (1, 3, 2)
listNumbers.add(5); // (1, 3, 2, 5)
System.debug('Size of list ' +listNumbers.size()); //4
listNumbers.set(1, 8); //put 8 at index 1
System.debug('List val ' +listNumbers); // (1, 8, 2, 5)
listNumbers.sort();
System.debug('List val ' +listNumbers); // (1, 2, 5, 8)
listNumbers.clear(); //clear the list
System.debug('List val ' +listNumbers); // ()
Reference of List methods:
Set
A sorted collection which does not allow duplicate value. If there is a duplicate, it removes from it.
Therefore, look at list section above.
Useful methods:
- .add(param) : Insert a value into the Set
- .size() : get the size of the Set
- remove(param) : remove an element of the Set
- contains(param) : check whether there is an element in the Set. True or False
- .clear() : clear the Set
Example:
Set<Integer> setNumbers = new Set<Integer>{1, 3}; //(1, 3)
//add member into Set
setNumbers.add(2); // (1, 2, 3)
System.debug('Size of Set ' +setNumbers.size()); //3
setNumbers.add(8); //put 8
setNumbers.add(1); //add duplicate value of 1
System.debug('Set val ' +setNumbers); // (1, 2, 3, 8)
System.debug('Set contains ' +setNumbers.contains(8)); //true
setNumbers.remove(8);
//get first element
for(Integer i : setNumbers) { System.debug(i); break; }
//get third element
Integer thirdNum = (new List(setNumbers)[2]);
System.debug('val of third num ' +thirdNum);
System.debug('Set val ' +setNumbers); // (1, 2, 3)
setNumbers.clear(); //clear the Set
System.debug('Set val ' +setNumbers); // ()
Reference of Set methods:
Map
- A collection with key-value pairs.
- Key and value can be any data type.
- Variations to define and initialise the map:
Map<Integer, String> countries = new Map<Integer, String>(); //{}
Map<String, String> myStrings = new Map<String, String>{'a' => 'x', 'b' => 'y'}; //{a=x, b=y}
Map<Id, Account> mapAccts = new Map<Id, Account>([SELECT Id, Name FROM Account LIMIT 1]);
//{0012x000004SNHTAA4=Account:{Id=0012x000004SNHTAA4, Name=KenCorp}}
//alternatively
List<Account> listAccts = [SELECT Id, Name FROM Account LIMIT 1];
Map<Id, Account> mapAccts = new Map<Id, Account>(listAccts);
//SOQL return List, hence use method below to get set ids
Set<Id> caseIds = new Map<Id,Case>([SELECT Id FROM Case LIMIT 10]).keyset();
//can nested with other collection
Map<Integer, List<Account>> mAccts = new Map<Integer, List<Account>>{1 => listAccts};
System.debug('val ' +mAccts); //val {1=(Account:{Id=0012x000004SNHTAA4, Name=KenCorp})}
System.debug('val ' +mAccts.get(1).get(0).Name); //KenCorp
Useful methods:
- .clear() : clear member of the map
- .containsKey(key) : return True if the map contains a mapping for the specified key.
- .get(key) : return value that map with the key
- .keySet() : return set that contains all keys in the map
- .put(key, value) : insert value into map with key and value specified
- .remove(key) : remove value that map with the key
- size() : return size of the map.
- values() : return a list / array that contains values in the map.
Useful Example combination List, Set, Map. Last Example below is useful
//Variations to initialise and assign value into Maps
Map<String, Integer> personAges = new Map<String, Integer>{'Andy' => 30}; //{Andy=30}
personAges.put('Tony', 25); //{Andy=30, Tony=25}
System.debug(personAges.size()); //2
personAges.remove('Andy'); //remove Andy from Map
System.debug(personAges); //{Tony=25}
//Query Account objects
List<Account> lstAllAccts = [SELECT Id, Name FROM Account];
//put list into Map
Map<Id, Account> mapAccts = new Map<Id, Account>(lstAllAccts);
//one way to traverse Map
for(Account mAccts: mapAccts.values()) {
System.debug('val in for: ' +mAccts); //Account:{Id=0012x000004SNHTAA4, Name=KenCorp}
System.debug('Name val in for:' +mAccts.Name); //KenCorp
}
//can nested with other collection
Map<Integer, List<Account>> mAccts = new Map<Integer, List<Account>>{1 => listAccts};
System.debug('val ' +mAccts.get(1)); //val {1=(Account:{Id=0012x000004SNHTAA4, Name=KenCorp})}
//combination of List, Set, and Map
List<Account> lstAccount = new List(); //create an empty list
Set<Id> accSet = new Set(); //create an empty set
//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map<Id,Account>([SELECT Id, Name, AccountNumber FROM Account]);
System.debug('Maps: ' +accountIdObjMap); //0012x000003X3kwAAC=Account:{Id=0012x000003X3kwAAC, Name=Edge Communications, AccountNumber=CD451796}
//another way to iterate Map
for(Id id:accountIdObjMap.keySet()) {
System.debug('Id: ' +id+ ' , acc name: ' +accountIdObjMap.get(id).Name);
}
//get value from map into List
lstAccount = accountIdObjMap.values();
//Assign Id from Map into Set
accSet = accountIdObjMap.keySet();
//combination of List, Set, and Map
List<Account> lstAccount = new List(); //create an empty list
Set<Id> accSet = new Set(); //create an empty set
//Creating Map with account id as key and account record as value
Map<Id,Account> accountIdObjMap = new Map([SELECT Id, Name, AccountNumber FROM Account]);
System.debug('Maps: ' +accountIdObjMap); //0012x000003X3kwAAC=Account:{Id=0012x000003X3kwAAC, Name=Edge Communications, AccountNumber=CD451796}
//another way to iterate Map
for(Id id:accountIdObjMap.keySet()) {
System.debug('Id: ' +id+ ' , acc name: ' +accountIdObjMap.get(id).Name);
}
//get value from map into List
lstAccount = accountIdObjMap.values();
//Assign Id from Map into Set
accSet = accountIdObjMap.keySet();
//use values() with advance example - Acc & Contact
Map<Id,Account> accMap = new Map([
SELECT Id, Name, (SELECT Id, LastName FROM Contacts) FROM Account
]);
//Iterate Map with Values()
for(Account acc: accMap.values()) {
System.debug('acc: ' +acc.Name);
for(Contact c : acc.contacts) {
System.debug('con: ' +c.LastName);
}
}
Reference of Map methods:
Exercises
1. Generate random numbers between 0 – 10 for 10 times using: Math.random() * 10. Count the occurrences of numbers and find the one that has the occurrences.
2. Generate random numbers between 0 – 10 for 10 times using: Math.random() * 10. Sum all elements.
3. Generate random numbers between 0 – 10 for 10 times using: Math.random() * 10. Display the largest elements.