The syntax for defining a list, map, and set collection with initial values sometimes slips my mind. The lack of () throws me off, so this post is to help out my future self.
List Definition
public list MyList = new list {'AAA', 'AAA', 'BBB', 'BBB', 'CCC'};
Set Definition
public set MySet = new <set>{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
Map Definition
public map<String, String> MyMap = new map<String, String> {'KeyValueA' => 'ValueA',
'KeyValueB' => 'ValueB',
'KeyValueC' => 'ValueC'};
Defining a List of Maps
public list<map<String, String>> MyListOfMaps = new list<map<String, String>>
{new map<String, String>
{'KeyValueA' => 'ValueA',
'KeyValueB' => 'ValueB',
'KeyValueC' => 'ValueC'
},
new map<String, String>
{'KeyValueA' => 'ValueA'
},
new map<String, String>
{'KeyValueA' => 'ValueA',
'KeyValueB' => 'ValueB'
}
};
Defining a Map of Lists
public map<String, list> MyMap = new map<String, list>
{'KeyValue1' => new list {'ValueA', 'ValueB', 'ValueC'},
'KeyValue2' => new list {'ValueD', 'ValueE', 'ValueF'},
'KeyValue3' => new list {'ValueG', 'ValueH', 'ValueI'}
};
Defining a Map of Maps
public map<String, map<String, String>> MyMap = new map<String, map<String, String>>
{'KeyValue1' => new map<String, String>
{'KeyValueA' => 'ValueA',
'KeyValueB' => 'ValueB',
'KeyValueC' => 'ValueC'
},
'KeyValue2' => new map<String, String>
{'KeyValueA' => 'ValueA'
},
'KeyValue3' => new map<String, String>
{'KeyValueA' => 'ValueA',
'KeyValueB' => 'ValueB'
}
};
Sample logic to retrieve the nested Map’s value
This function accepts Param1 as the key for the outer map. Param2 is the key for the inner map. TheMap is a map that contains a nested map which will be worked with. First, we see if there is a key value in the outer map that matches Param1. When it contains the key, the next statement creates a reference to the inner map in the variable TempMap. TempMap is checked for the value of Param2, and the value is returned when found. Finally, null is returned when there is not a match.
public static String GetInnerMapValue(String Param1, String Param2, map<String, map<String, String>> TheMap) {
map<String, String> TempMap;
if (TheMap.containsKey(Param1)) {
TempMap = TheMap.get(Param1);
if (TempMap.containsKey(Param2) return TempMap.get(Param2);
}
// map values were not found, so return something else
return null;
}