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
Dippan PatelDippan Patel 

Convert list of SObject to Map

Hi, 

I have a below list: 

List<Sobject> sObj =
Sobject: (Test_Lead_Sources__c:{Id=null, OwnerId=005d0000003vn6BAAQ, IsDeleted=false, Name=test, CreatedDate=null, CreatedById=null, LastModifiedDate=null, LastModifiedById=null, SystemModstamp=null, LastViewedDate=null, LastReferencedDate=null, Primary_Source__c=test, Active__c=false})

It can have any number of records here. 

Plus this can have any custom SObject. 

I want to get the name of Custom Object here which is Test_Lead_Sources__c and list of all the records in it. 

How do I convert this list to map in such a way that I can get name of SObject? Or what is the other possible way? 
 
Best Answer chosen by Dippan Patel
Shruthi ChandrasekaranShruthi Chandrasekaran
Hello Dippan, 

You can get the name of the Sobject using the method getSObjectType(); Try the below code where I have used Map to store the SobjectType and the List of all records of that Sobject. 
Map<Schema.SObjectType, List<SObject>> objMap = new Map<Schema.SObjectType, List<SObject>>();
for(Sobject obj : sObj){
    Schema.SObjectType o = obj.getSObjecttype();
    System.Debug(o);
    if(objMap.containsKey(o)){
        objMap.get(o).add(obj);
    }
    else {
        objMap.put(o, new List<SObject>{obj});
    }
}
System.Debug(objMap);
If this code helps, please mark the answer as best answer as it help others as well.

Thanks
Shruthi