Maps of sObjects
1Map<ID, Account> m = new Map<ID, Account>();As with primitive types, you can populate map key-value pairs when the map is declared by using curly brace ({}) syntax. Within the curly braces, specify the key first, then specify the value for that key using =>. This example creates a map of integers to accounts lists and adds one entry using the account list created earlier.
1Account[] accs = new Account[5]; // Account[] is synonymous with List<Account>
2Map<Integer, List<Account>> m4 = new Map<Integer, List<Account>>{1 => accs};Maps allow sObjects in their keys. You must use sObjects in the keys only when the sObject field values won’t change.
Auto-Populating Map Entries from a SOQL Query
When working with SOQL queries, maps can be populated from the results returned by the SOQL query. The map key must be declared with an ID or String data type, and the map value must be declared as an sObject data type.
1// Populate map from SOQL query
2Map<ID, Account> m = new Map<ID, Account>([SELECT Id, Name FROM Account LIMIT 10]);
3// After populating the map, iterate through the map entries
4for (ID idKey : m.keyset()) {
5 Account a = m.get(idKey);
6 System.debug(a);
7}One common usage of this map type is for in-memory “joins” between two tables.
Using Map Methods
The Map class exposes various methods that you can use to work with map elements, such as adding, removing, or retrieving elements. This example uses Map methods to add new elements and retrieve existing elements from the map. This example also checks for the existence of a key and gets the set of all keys. The map in this example has one element with an integer key and an account value.
1Account myAcct = new Account(); //Define a new account
2Map<Integer, Account> m = new Map<Integer, Account>(); // Define a new map
3m.put(1, myAcct); // Insert a new key-value pair in the map
4System.assert(!m.containsKey(3)); // Assert that the map contains a key
5Account a = m.get(1); // Retrieve a value, given a particular key
6Set<Integer> s = m.keySet(); // Return a set that contains all of the keys in the map