Define and Initialize a Map, List, and Set in Apex

20 Oct

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

Set Definition

Map Definition

Defining a List of Maps

Defining a Map of Lists

Defining a Map of Maps

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.

5 Replies to “Define and Initialize a Map, List, and Set in Apex

  1. Thanks for the help Dave.. Could you please elaborate nested maps more and in Sample logic to retrieve the nested Map’s value , what is TheMap. Please explain.

  2. This is absolutely fantastic! I could not, for the life of me, recall how my supervisor had instantiated a map with string key with a set of name value pairs, and your blog post saved me a huge headache via the “compile-until-I-guess-the-correct-syntax” method. I was forgetting to instantiate the inner set with the new set part. Ahh, so glad you wrote this up as the rest will help structuring data at some point. Thank you so much Dave!

  3. Dave, I have this bookmarked and don’t even bother trying to remember syntaxes. I just come here when I need to write Apex. THANK YOU!

Comments are closed.