0

This question already has an answer here:

Here is my Map

Map<id,List<Custom_Report_2__c>> mapreports= new Map<id,List<Custom_Report_2__c> >();
for( Custom_Report_2__c  cr:cr1){
     mapreports.put(cr.Associated_Loan__c,new List<Custom_Report_2__c>());
     mapreports.get(cr.Associated_Loan__c).add(cr);
}

Even mapreports stores only one record where as there has to be 200 records :( This list of Custom report has 200 records per id. when i try to get all the records thru for loop i get only i record per id with its list.

for(list<Custom_Report_2__c> ad : mapreports.values()){
     system.debug('a'+ad);
}

This for loops accepts only list <Custom_Report_2__c> how do i store all the values for the map returned.

Correct me if my declarations are wrong.

marked as duplicate by David Reed, glls, battery.cord, Brian Mansfield, Himanshu Aug 17 '18 at 15:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

3

Try like this

Map<id,List<Custom_Report_2__c>> mapreports= new Map<id,List<Custom_Report_2__c> >();
for( Custom_Report_2__c  cr:cr1){
     //it will check if the Associated_Loan__c already exist in map or not. 
     // if not then put the first value into map as key and value
     if(!mapreports.containsKey(cr.Associated_Loan__c)){
        mapreports.put(cr.Associated_Loan__c,new List<Custom_Report_2__c>{cr});

     }
     else{//here since the Associated_Loan__c already exist then 
          //it will get the existing list of Custom_Report_2__c and add into the list
         mapreports.get(cr.Associated_Loan__c).add(cr);
     }
}

for(Id al:mapreports.keySet()){
      system.debug(al+'====key=====values=='+mapreports.get(al));
}
1

This is because each time you are initializing a new list inside your map, that overwrite your old vales.

So you need to keep track of your old value and if your map doesn't have the key then only you should initialize.

Map<id,List<Custom_Report_2__c>> mapreports= new Map<id,List<Custom_Report_2__c> >();
for( Custom_Report_2__c  cr:cr1){
     if(!mapreports.containsKey(cr.Associated_Loan__c)) //first check if key exisyt, if not add then only initialize
        mapreports.put(cr.Associated_Loan__c,new List<Custom_Report_2__c>);

     mapreports.get(cr.Associated_Loan__c).add(cr);  
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.