0

I have to populate a set of Ids with Ids derived from a List<List<sObject>> say searchlist. Below code as I am trying gives me System.Final Exception as Collection is read only and prevents me to copy over Ids from Set<Id> tempids to Set<Id> accids.

Apex Code

  accids = new Map<Id,SObject>(searchList[0]).keySet();
        for(List<sObject> s: searchList)
        tempids = (new Map<Id,SObject>(s)).keySet();
        accIds.addall(tempids);

Can someone please let me know what's wrong going on here?

  • 2
    Try this: ` new Map<Id,SObject>(searchList[0]).keySet().clone()`. Map keysets are read only. – Caspar Harmer May 12 '18 at 7:17
  • 1
    Please share correct code. This code is incomplete/incorrect. for loop don't have brackets. Assigning map to set. I doubt this is correct code. – Tushar Sharma May 12 '18 at 8:21
  • @CasparHarmer How should I keep the clone? I need to put inside the for loop? – Testing_SFDC May 12 '18 at 11:13
0

Caspar's comment explains the problem. You are trying to use the keySet() of a Map in a way that is not intended: those are intended to simplify code that reads the values and are not intended for use as a general purpose set.

So instead create your own mutable (writeable) set:

Set<Id> accIds = new Set<Id>();
for(List<sObject> sob: searchList) {
    Set<Id> tempIds = (new Map<Id,SObject>(sob)).keySet();
    accIds.addAll(tempIds);
}

Personally I would write the logic like this:

Set<Id> accIds = new Set<Id>();
for(List<sObject> sobs: searchList) {
    for(sObject sob: sobs) {
        accIds.add(sob.Id);
    }
}
  • Hi @Keith I tried with both of your suggested codes and it's giving the same error. – Testing_SFDC May 12 '18 at 11:12
  • 1
    @SFDC_Learner Well that is weird. If you want to use the searchList[0] approach, do make sure that searchList is not empty as that will blow up if it is. – Keith C May 12 '18 at 11:33
0

Thanks everyone! I was able to fix the issue with Caspar Hammer's suggestion. Thanks!

 accids = new Map<Id,SObject>(searchList[0]).keySet().clone();

for(List<sObject> sob: searchList) {
    Set<Id> tempIds = (new Map<Id,SObject>(sob)).keySet();
    accIds.addAll(tempIds);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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