anusha(salesforce developer)

SFDC Data collections List-Set-Map

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

other examples to declare List
=>  String[] colors = new List<String>();  // String list with no element in it
=>  List<Integer> ints = new Integer[6];   // List with memory allocated for six elements , ints[0] return null
=>  List<Account> accts = new Account[]{}; // Account list with no element
Account act = new Account();
act.name ='Varun Corp';
accts.add(act);
=>  List<Account> accts = new Account[]{null,null};
=>  List<Account> newActList = new List<Account>(accts); // list created using other list of same type
        Try following example and check output debug message
           
            List<Account> accts = new Account[]{};
            Account act = new Account();
            act.name ='Varun';
            accts.add(act);
            List<Account> newActList = new List<Account>(accts);
            accts.get(0).Name = 'Tinku';
            System.debug(accts[0].name+'            '+newActList[0].name);
   
=>  List<Lead> leadList = [Select Id,Name from Lead LIMIT 100]; // Creating list using SOQL query

List Sorting:

List.sort ( used to sort list in  assending order for premitive data type (Integer,String etc. ).
       
a)Sorting of Nonpremitive data type (custom types (your Apex classes)) the check out Comparable Interface)

b)Sorting list of sObject : 
            Account[] acctList = new List<Account>();
            Account act1 = new Account();
            act1.name = 'XYZ Corp';
            Account act2 = new Account();
            act2.name = 'ABC Corp';
            acctList.add(act1);
            acctList.add(act2);   
            acctList.sort();
            System.debug(acctList[0].Name) ; // ABC Corp
            System.debug(acctList[1].Name) ; // XYZ Corp
Note : Sorting for sObject happen first on Name field then use other standard fields in alphabatical order.

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<String> st = new Set<String>();
        st.add('king'); // add
        st.add('kong'); // add
        System.debug(st.contains('king')); // true
        st.add('king'); // add
        System.debug(st.size()); // return 2

        //Note we have added three entries but system returned set size as 2

        // 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
      

   
    Map is also an Unordered Collection

    Example1 : country_name and country_code
            India  -  91
            USA  -   1   
            UK    -  44   

        Map<String,Integer> countryCodeMap = new Map<String,Integer>();

        countryCodeMap.put('India',91);
        countryCodeMap.put('USA',1);
        countryCodeMap.put('UK',44);

        for(String ky : countryCodeMap.keySet()){
            System.debug(countryCodeMap.get(ky));
        } // output will be Unordered
       
    Example2: Map on Account Name and Account sObject
       
        Map<String,Account> actName = new Map<String,Account>();
        Account act1 = new Account();
        act1.Name = 'ABC';
        Account act2 = new Account();
        act2.Name = 'DEF';
        Account act3 = new Account();
        act3.Name = 'XYZ';

        actName.put(act1.Name, act1);
        actName.put(act2.Name, act2);
        actName.put(act3.Name, act3);

        for(String recKey: actName.keySet()){ 
            // Map.KeySet() return key Set ( Set has property to have unique values )
            System.debug(actName.get(recKey));
        } // output will be Unordered

    Example3: Can create Map using SOQL query
       
        Map<Id,Account> actMap = new Map<Id,Account>([select Id,name from account LIMIT 10]);

        for(Id recId : actMap.keySet()){
        System.debug(actMap.get(recId).Name);
        }

   
About List,Set,Map and sObject ( sObject can accomodate any standard or custom SFDC object )
   
     List<sObject> lstSObject = new List<sObject>();
       Account act = new Account(Name='ABC');
       Contact cnt = new Contact(LastName='Smith');   
       lstSObject.add(act);
       lstSObject.add(cnt);

       for(sObject s : lstSObject){
        System.debug(s.getSObjectType());
        if(s instanceof Account)
        System.debug(((Account)s).Name);
        if(s instanceof Contact)
        System.debug(((Contact)s).LastName);

       }
===================================================================

1) List: List is an ordered collection of elements which will allow duplicates.
Syntax:
List<datatype> listName = new List<datatype>();
– The datatype allows both primitive datatypes and non-primitive datatypes
– Size of the list is dynamically increased.

Methods in List

Add: Add the values to the list.
Ex: List<String> colors =new List<String>();
colors.add(‘Red’);
colors.add(‘White’);
colors.add(‘Black’); (OR)
List<String> colors =new List<String>{‘Red’,’White’,’Black’}
Get: Retrieve a values from list using index.
String getcolor = colors.get(1); —- we get the value is ‘White’ in to getcolor veriable.
Set: Replaces a former value with the value at given index.
colors.set(1,’Green’); —- List has value at index ‘ 1 ‘ is White is changed to Green.
Size: Return the number of elements in the list.
colors.size(); —- Gives the size of colors list is ‘2’
Clear: Remove the elements from the list.
colors.clear();

Please check below link for more example
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_lists.htm

2) Set is an unordered collection of elements which will not allow duplicates.

Syntax

set<datatype> setName = new set<datatype>();

data type allows only primitive datatypes and SObjects.
We cannot get the retrieve the data based on index because set does not  have index.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_sets.htm

3) Map

Map is key – value pairs.

Syntax

map<datatype,datatype> mapName = new map<datatype,datatype>();


Methods
Put()

Insert a key-value pair or replaces a value with the given value for the key .

   map.put(key,value);

Get()

Retrieves the value for a key.

map.get(key);

keySet()

Retrieves all the keys and return type is set;

map.keySet();

values()

Retrieves all the values and return type is list;

map.values();

Size()

Return the number of components in the map.

map.size();

Example: Create a map of Account Ids and Account objects.

public class AccountMapPopulation{

// Creating map with account id and account object

map <Id,Account> accountIdMap =new map<Id,Account>();

public void methodName(){

// creating the accounts

account acc1 = new account (name =’account1′ , industry = ‘ Banking’);

account acc2 =new account(name =’ account2′ , industry = ‘Agriculture’);

account acc3 = new account(name=’account3′ , industry=’Banking’);

// populating the map with account id and account object

accountIdMap .put(acc1.id,acc1);

accountIdMap .put(acc2.id,acc2);

accountIdMap .put(acc3.id,acc3);

}

}
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_maps.htm

First datatype is key and it allows primitive datatypes and should be unique.
Second datatype is values and it allows both primitive & non-primitive datatypes and allows duplicates.

No comments:

Post a Comment