How to define and initialize a Map, List, and Set with Apex

Many times when writing apex code we forgot to write the syntax for defining a list, map, and set collection with their initial values. That’s why this post is here, to remind ourselves, to write good apex code.

List Definition
public List<String> myList = new List<String> {'AAA', 'AAA', 'BBB', 'BBB', 'CCC'};
Map Definition
public Map<String, String> myMap = new Map<String, String> {'KeyValue1' => 'Value1', 
                                                            'KeyValue2' => 'Value2', 
                                                            'KeyValue3' => 'Value3'};
Set Definition
public Set<String> mySet = new Set<String>{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
Defining a Map of Lists
public Map<String, List<String>> myMap = new Map<String, List<String>>
  {'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

Join US!

Share this article...

Darko Todorovski

Salesforce Maniac for 7 years, Hardcore Admin & Developer, Geek, Animal lover, and dog & cat rescuer activist. Lifetime student, Stand-Up comedian wannabe, Photographer, Gamer, Anime lover, and coffee addict. Spreading salesforce love and teaching beyond my capacity. Aiming to become Tech Architect!

Leave a Reply

Your email address will not be published. Required fields are marked *