Collection initialization

Apex collections support better initialization syntax than Java collections:

List<String> l = new List<String>{'a', 'b', 'c'};
Set<String> s = new Set<String>{'a', 'b', 'b'};
Map<String, String> m = new Map<String, String>{'a' => 'x', 'b' => 'y', 'c' => 'z'};

This means clearer code and the possibility of skipping the assignment to a variable if the collection is being created just as an argument to a method. The normal array initialization is also available and can be used interchangeably with the list initialization.

Plus there is this magical map initialization which automatically populates the key of the map with the Id of the object and the value with the object:

Map<Id, Contact> m = new Map<Id, Contact>([select Id, LastName from Contact]);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s