Tuesday, March 3, 2015

Populating Map + SFDC

Many times I faced that I need a Value with its "Group of values".

Getting a unique value in Set is a idea, but what if you have a group of values associated with it.

So that time Map is the best way to settle it down.
we can take Map in many ways but here I am using
Map<String, List<String>>

I used this map allot, because populating this map with Key and Values is a great method.
Here am showing two methods same but in different ways.

Here is the first one.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    //Map of Opportunity
    Map<Id, Set<Id>> opportunityMap = new Map<Id, Set<Id>>();

    //Loop through the Opportunity records
    for(Opportunity opp : opportunities) {
     
        //Check if map key contains System Field
        if(opportunityMap.containsKey(opp.Opportunity_Field__c)) {
         
          //Get the Values of the Map and add Id to it.
          opportunityMap.get(opp.Opportunity_Field__c).add(opp.Id);
        }else {
          //Creat a new Set at values and add Id to it.
          opportunityMap.put(opp.Opportunity_Field__c, new Set<Id>{opp.Id}); 
        }
      }
    }

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


Here is the same but another way to write it
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

//Loop through list
for(Opportunity opp : opportunities) {

   //List of Opportunity
   List<Opportunity> opps = new List<Opportunity>();

  //Check for values of the Map
   if(mapOpportuinties.containsKey(opp.Fishbowl_Customer_Number__c) == false) {

    //Add to list
   opps.add(opp);

  } else {

     //Add to list
     opps = mapOpportuinties.get(opp.Fishbowl_Customer_Number__c);
     opps.add(opp);
  }

     //Populating map
     mapOpportuinties.put(opp.Fishbowl_Customer_Number__c, opps);
  }

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Using the above snippet every unique value will have a common group of values. its like

Object1 = value1, value2 value3
Object2 = value1, value2, value3
Object3 = value2, value3, value4
Object4 = value5, value6, value7


Cheers....!!!!!