Wednesday, 9 October 2013

Populating Map Using Loops


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.

1:  //Map of Opportunity  
2:    Map<Id, Set<Id>> opportunityMap = new Map<Id, Set<Id>>();  
3:    //Loop through the Opportunity records  
4:    for(Opportunity opp : opportunities) {  
5:      //Check if map key contains System Field  
6:      if(opportunityMap.containsKey(opp.Opportunity_Field__c)) {  
7:       //Get the Values of the Map and add Id to it.  
8:       opportunityMap.get(opp.Opportunity_Field__c).add(opp.Id);  
9:      }else {  
10:       //Creat a new Set at values and add Id to it.  
11:       opportunityMap.put(opp.Opportunity_Field__c, new Set<Id>{opp.Id});   
12:      }  
13:     }  
14:    }  

Here is the same but another way to write it

1:  //Loop through list  
2:  for(Opportunity opp : opportunities) {  
3:    //List of Opportunity  
4:    List<Opportunity> opps = new List<Opportunity>();  
5:   //Check for values of the Map  
6:   &#160 if(mapOpportuinties.containsKey(opp.Fishbowl_Customer_Number__c) == false) {  
7:    //Add to list  
8:    opps.add(opp);  
9:   &#160} else {  
10:     //Add to list  
11:     opps = mapOpportuinties.get(opp.Fishbowl_Customer_Number__c);  
12:     opps.add(opp);  
13:   }  
14:     //Populating map  
15:     mapOpportuinties.put(opp.Fishbowl_Customer_Number__c, opps);  
16:   }  

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....!!!!!
Happy Coding.

2 comments:

  1. Nice Information Your first-class knowledge of this great job can become a suitable foundation for these people. I did some research on the subject and found that almost everyone will agree with your blog.
    Cyber Security Course in Bangalore

    ReplyDelete
  2. Writing in style and getting good compliments on the article is hard enough, to be honest, but you did it so calmly and with such a great feeling and got the job done. This item is owned with style and I give it a nice compliment. Better!
    Cyber Security Training in Bangalore

    ReplyDelete