function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Andrew GrayAndrew Gray 

check nested map

When looping the list aes - I want to know if a Trading_Relationship__c exists with same Cust__c/Supp__c values. Am trying to put all TRs into nested list to check against. Is that easiest way and how do I check in the loop? Thanks
 
List<Trading_Relationship__c> trs = [SELECT Id, Customer__c, Supplier__c FROM Trading_Relationship__c];  
Map<Id, List<Id>> trmap = new Map<Id, List<Id>>();
for(Trading_Relationship__c tr: trs) {
trmap.put(tr.Customer__c, new List<Id>());
}  
for(Trading_Relationship__c tr: trs) {
trmap.get(tr.Customer__c).add(tr.Supplier__c);
}


for(Agent_Engagements__c ae: aes) {
//ae.Cust__c
//ae.Supp__c
??
}


 
Best Answer chosen by Andrew Gray
Tyler Brooks 22Tyler Brooks 22
Please try below code. Note you dont need to loop through the list twice to first add the key with an empty list and the again to add the supplie to the list for the customer. You can simply check if the customer has already been added and if not add a blank list and in the same record add to the list for that customer.
List<Trading_Relationship__c> trs = [SELECT Id, Customer__c, Supplier__c FROM Trading_Relationship__c];  
Map<Id, List<Id>> trmap = new Map<Id, List<Id>>();
for(Trading_Relationship__c tr: trs) {
    if(!trmap.containsKey(tr.Customer__c)) {
        trmap.put(tr.Customer__c, new List<Id>());
    }
    trmap.get(tr.Customer__c).add(tr.Supplier__c);
}  
for(Agent_Engagements__c ae: aes) {
 if(trmap.containsKey(ae.Customer__c)) {
    if(trmap.get(ae.Customer__c).contains(ae.Supplier__c)) {
        //do something
    }
 }
}

 

All Answers

Tyler Brooks 22Tyler Brooks 22
Please try below code. Note you dont need to loop through the list twice to first add the key with an empty list and the again to add the supplie to the list for the customer. You can simply check if the customer has already been added and if not add a blank list and in the same record add to the list for that customer.
List<Trading_Relationship__c> trs = [SELECT Id, Customer__c, Supplier__c FROM Trading_Relationship__c];  
Map<Id, List<Id>> trmap = new Map<Id, List<Id>>();
for(Trading_Relationship__c tr: trs) {
    if(!trmap.containsKey(tr.Customer__c)) {
        trmap.put(tr.Customer__c, new List<Id>());
    }
    trmap.get(tr.Customer__c).add(tr.Supplier__c);
}  
for(Agent_Engagements__c ae: aes) {
 if(trmap.containsKey(ae.Customer__c)) {
    if(trmap.get(ae.Customer__c).contains(ae.Supplier__c)) {
        //do something
    }
 }
}

 
This was selected as the best answer
Andrew GrayAndrew Gray
Great - that helps. Many thanks