In Apex, you can create any sort of
map. The first thing to consider is the structure of a
map / how it works. A
map contains two elements: the
keyset and the
keyset, as the name implies, is a
set -- therefore it stores no duplicate values. The map's
values is a
list -- so it can have duplicate values.
To create a map, first you need to construct it, so let's create a fresh new map to work with:
map<string,integer> myFirstMap = new map<string,integer>();
Now, we need to put elements into the map. By the way we defined our map, it takes
strings as its input and gives
integers as its output. So, let's give our map some elements. Use the
put method to insert elements into the map.
Now to get the value, use the
get method of the map.
integer a_value = myFirstMap.get('a');
To access the map's
values, use the
values() methods, respectively.
set<string> theKeyset = myFirstMap.keyset();
list<integer> theValues = myFirstMap.values();
And that's pretty much it for the map methods. The big thing to consider is that the keyset is a set. What if you do the following?
system.assertEquals(myFirstMap.get('hey there', xxxx ); // what's xxxx?
// answer: xxxx = 420
The map will store only the last value given for a specific key. Another consideration is "What happens if you try to get a key that has never been set?"
system.assertEquals(myFirstMap.get('this key has never been set X_X'),null);
Now to specifically address your question: Suppose we want to get a
list<Account> via SOQL query and then create a map with the Account's
OpportunityID as its key.
list<Account> accountList = [SELECT id,OpportunityID
map<id,Account> oppIdAcctMap = new map<id,Account>();