Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code used in map basic methods tutorial on SFDC Stop (https://youtu.be/MKqylTF4yGo)
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