Apex Inline List and Map Definition

I’m making this post because, frankly, I always forget the syntax.

There’s a long-form way to define a List or String in apex, and there’s also an equivalent short-form way to define a List or String variable inline. Here’s the long-form:

List<String> stringList = new List<String>();
stringList.add('a');
stringList.add('b');

Map<String, String> stringMap = new Map<String, String>();
stringMap.put('a', 'b');
stringMap.put('c', 'd');

3 lines for 2 pre-defined values? Gimme a break, man! Here’s the short-form:

List<String> stringList = new List<String> {'a', 'b'};

Map<String, String> stringMap = new Map<String, String> {'a' => 'b', 'c' => 'd'};

Feels much cleaner, right? This is defined in the “Using Collections” (pp. 19-20 of Spring ’11) section of the Force.com Apex Code Developer’s Guide (pdf).

List <datatype> list_name
[= new List<datatype>();] |
[=new List<datatype>{value [, value2. . .]};] |
;
This entry was tagged , , . Bookmark the permalink.