Created
November 20, 2021 13:12
-
-
Save rahulmalhotra/d677d1cc8c4222a80009a0464dc30630 to your computer and use it in GitHub Desktop.
Code used in map basic methods tutorial on SFDC Stop (https://youtu.be/MKqylTF4yGo)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Map Data Structure in Apex | |
------------------------------- | |
Def: A map is a collection of key-value pairs where each unique key maps to a single value. | |
1. Creating a Map of Employees | |
------------------------------- | |
Map<Integer, String> employeesMap = new Map<Integer, String>(); | |
System.debug(employeesMap); | |
Map<Integer, String> employeesMap = new Map<Integer, String>{ | |
1 => 'Richard', | |
2 => 'Monica', | |
3 => 'Erlich', | |
4 => 'Dinesh' | |
}; | |
System.debug(employeesMap); | |
2. Adding elements to the map | |
------------------------------ | |
Map<Integer, String> employeesMap = new Map<Integer, String>(); | |
System.debug(employeesMap); | |
employeesMap.put(1, 'Richard'); | |
employeesMap.put(2, 'Monica'); | |
employeesMap.put(3, 'Erlich'); | |
employeesMap.put(4, 'Dinesh'); | |
System.debug(employeesMap); | |
3. Accessing elements from the map | |
----------------------------------- | |
Map<Integer, String> employeesMap = new Map<Integer, String>{ | |
1 => 'Richard', | |
2 => 'Monica', | |
3 => 'Erlich', | |
4 => 'Dinesh' | |
}; | |
System.debug(employeesMap); | |
// System.debug('Employee with id 3 = ' + employeesMap.get(3)); | |
System.debug('Employee with id 10 = ' + employeesMap.get(10)); | |
4. Removing element from the map | |
----------------------------------- | |
Map<Integer, String> employeesMap = new Map<Integer, String>{ | |
1 => 'Richard', | |
2 => 'Monica', | |
3 => 'Erlich', | |
4 => 'Dinesh' | |
}; | |
System.debug('Initial Map = ' + employeesMap); | |
System.debug('Removing Employee with Id 4...'); | |
employeesMap.remove(4); | |
System.debug('Final Map = ' + employeesMap); | |
5. Checking if the element is present in the map or not | |
--------------------------------------------------------- | |
Map<Integer, String> employeesMap = new Map<Integer, String>{ | |
1 => 'Richard', | |
2 => 'Monica', | |
3 => 'Erlich', | |
4 => 'Dinesh' | |
}; | |
System.debug('Initial Map = ' + employeesMap); | |
System.debug('Is Employee with id 3 present? => ' + employeesMap.containsKey(3)); | |
System.debug('Is Employee with id 100 present? => ' + employeesMap.containsKey(100)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment