Tuesday, May 28, 2013

SFDC Data collections List-Set-Map

Salesforce APEX collections: Salesforce provides three different types of collections.

A) List
B) Set
C) Map

Considering APEX governor limits ( that there limitation with APEX programming e.g. LIMITS on number of DMLs, number of rows retrieved etc. ), you should be good in using collections. Otherwise you may run into governor limits errors.

A) List : List is collection which contains Integer indexd data.

E.g. a list of String
List<String> lstNames = new List<String>();
lstNames.add('King'); // add is the way to add data to list
lstNames.add('Kong');

// you can retrive list entries as following
System.debug(lstNames[0]); // return King
System.debug(lstNames.get(1)); // return Kong

c) Custom Sort Order of sObjects : write wrapper on sObject then implement comparable and sort by the wrapper object. Try coding it.

How to use list with SOQL
List<String> actNameList = new List<String>();
actNameList.add('ABC COPR');
actNameList.add('XYZ COPR');
List<Account> actList = [select Id,Name from Account where Name in :actNameList];

B) Set : A set is an Unordered collection of elements that Do Not Contain any Duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

// Set is unordered collection
// following is the way to loop around set
for(String s: st){
System.debug(s);
}

How to use Set with SOQL
Set<String> actNameList = new Set<String>();
actNameList.add('ABC COPR');
actNameList.add('XYZ COPR');
List<Account> actList = [select Id,Name from Account where Name in :actNameList];

C) Map: A map is a collection of key-value pairs where each unique key maps to a single value. Keys and values can be any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.