0

I Have a map that includes a URL as the Key and a List of a custom object for the value. When two objects both have the same URL I would expect them both to be added to the List In the map. Right now the code is only returning 1 value for the URL. I originally had this functioning as a normal map that returns one value but Needed to add a way to tell if there were more than one Object for each URL. Code below.

        Set<String> urls = new Set<String>();
        for(Integer i=0; i < triggerNew.size(); i++){
        Case newCase = triggerNew[i];
            if(newCase.AppURL__c != null){
                urls.add(newCase.AppUrl__c); }
        }
    Map<String, List<MobileCloud_Website__c>> websites = new Map<String, List<MobileCloud_Website__c>>();
    List<MobileCloud_Website__c> webbys = new List<MobileCloud_Website__c>();

        for (MobileCloud_Website__c website : [
            SELECT Account__c, URL__C
            FROM MobileCloud_Website__c
            WHERE URL__c IN :urls AND Account__r.Account_Type_new__c != 'Inactive Customer'
        ]) {
            webbys.add(website);
            websites.put(website.URL__c, webbys);
        System.debug(webbys);
        }
    System.debug(websites);
    for(Integer i=0; i < triggerNew.size(); i++){
        Case newCase = triggerNew[i];
        List<MobileCloud_Website__c> website = websites.get(newCase.AppUrl__c);
        System.debug(website.size());
        If(website.size() == 1){
        newCase.AccountId = website[0].Account__c;
        }
    }

}

1 Answer 1

2

You need to create separate List objects for each key. Here's the pattern I use:

MobileCloud_Website__c[] webbys;
for (MobileCloud_Website__c website : [
    SELECT Account__c, URL__C
    FROM MobileCloud_Website__c
    WHERE URL__c IN :urls AND Account__r.Account_Type_new__c != 'Inactive Customer'
]) {
    if((webbys = websites.get(website.URL__c)) == null) {
        websites.put(website.URL__c, webbys = new MobileCloud_Website__c[0]);
    }
    webbys.add(website);
}
2
  • This worked perfectly, Thank you so much!
    – Trace
    Commented Feb 7, 2020 at 20:54
  • @Trace You're welcome!
    – sfdcfox
    Commented Feb 7, 2020 at 21:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .