List Definition
In Apex, a List is an ordered collection of elements. You can define a List with a specific data type, such as:
public List<String> myList = new List<String> {'AAA', 'AAA', 'BBB', 'BBB', 'CCC'};
This initializes the list with predefined values, making it easier to manage and access ordered data.
Map Definition
In Apex, a Map is a collection of key-value pairs. You define a Map by specifying the key and value types, like
public Map<String, String> myMap = new Map<String, String> {'KeyValue1' => 'Value1',
'KeyValue2' => 'Value2',
'KeyValue3' => 'Value3'};
This allows you to store and retrieve data based on unique keys.
Set Definition
In Apex, a Set is an unordered collection of unique elements. You define a Set by specifying its data type, such as
public Set<String> mySet = new Set<String>{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
This ensures that each element in the Set appears only once, making it useful for managing distinct values.
Defining a Map of Lists
public Map<String, List> myMap = new Map<String, List>
{'KeyValue1' => new list {'Value1', 'Value2', 'Value3'},
'KeyValue2' => new list {'Value4', 'Value5', 'Value6'},
'KeyValue3' => new list {'Value7', 'Value8', 'Value9'}
};
Defining a Map of Maps
public Map<String, map<String, String>> myMap = new Map<String, Map<String, String>>
{'KeyValue1' => new Map<String, String>
{'KeyValue1.1' => 'Value1',
'KeyValue1.2' => 'Value2',
'KeyValue1.3' => 'Value3'
},
'KeyValue2' => new Map<String, String>
{'KeyValue2.1' => 'Value1'
},
'KeyValue3' => new Map<String, String>
{'KeyValue3.1' => 'Value1',
'KeyValue3.2' => 'Value2'
}
};
Sample logic to retrieve the nested Map’s value
This function accepts ParamA as the key to the outer map. ParamB is the key to the inner map. TheMap is a map that contains a nested map that will be worked with. First, we see if there is a key value in the outer map that matches ParamA. 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 ParamB, and the value is returned when found. Finally, null is returned when there is not a match.
public static String getInnerMapValue(String ParamA, String ParamB, Map<String, Map<String, String>> TheMap) {
Map<String, String> tmpMap;
if (TheMap.containsKey(ParamA)) {
tmpMap = TheMap.get(ParamA);
if (tmpMap.containsKey(ParamB)
return tmpMap.get(ParamB);
}
//no Map values were found, return null
return null;
}
Want to learn more?
Learn about How to write your first Salesforce apex trigger
Read more about Apex Developer Guide – Maps
Check out this Trail: Define Sets and Maps
Map of lists need to be changed to:
public Map<String, List> myMap = new Map<String, List>
{‘KeyValue1’ => new list {‘Value1’, ‘Value2’, ‘Value3’},
‘KeyValue2’ => new list {‘Value4’, ‘Value5’, ‘Value6’},
‘KeyValue3’ => new list {‘Value7’, ‘Value8’, ‘Value9’}
};
Thank you Steven, I don’t know how that passed my eyes 🙂