+ Start a Discussion
Vershley JoyejobVershley Joyejob 

Create a map of Task and Contact. Map <Task, Contact>, any ideas please?

Hello, 

Any ideas on how I can create a map of Task and Contact, like this Map<Task, Contact> by using the WhoId from Task. I already have the Ids of Tasks that should be processed.

Thank you for your help.

Regards,
Vershley
Best Answer chosen by Vershley Joyejob
Vershley JoyejobVershley Joyejob
Got it like this, feel free to post your answers if you have anything better :)

 
List<Task> taskList = [SELECT Id, whoId, ActivityDate, whatId, Description, Status, subject FROM Task WHERE WhoId != null];
        Set<Id> contactIdSet = new Set<Id>();
        Map<Task, Id> taskByContactIdMap = new Map<Task, Id>();
        
        for(Task tsk : taskList){
            if(tsk.WhoId != null){
                contactIdSet.add(tsk.WhoId);
                taskByContactIdMap.put(tsk, tsk.WhoId);
            }            
        }
                

        Map<Id, Contact> contactByIdMap = new Map<Id, Contact>();
        
        for(Contact cnt : [SELECT Id, Name, Phone, MobilePhone, Title, Email FROM Contact WHERE Id IN :contactIdSet]){
            contactByIdMap.put(cnt.Id, cnt);
        }
        
        Map<Task, Contact> taskByContactMap = new Map<Task, Contact>();
        for(Task tsk : taskList){
            taskByContactMap.put(tsk, contactByIdMap.get(taskByContactIdMap.get(tsk)));       
            
        }

Thanks!

All Answers

Vershley JoyejobVershley Joyejob
Got it like this, feel free to post your answers if you have anything better :)

 
List<Task> taskList = [SELECT Id, whoId, ActivityDate, whatId, Description, Status, subject FROM Task WHERE WhoId != null];
        Set<Id> contactIdSet = new Set<Id>();
        Map<Task, Id> taskByContactIdMap = new Map<Task, Id>();
        
        for(Task tsk : taskList){
            if(tsk.WhoId != null){
                contactIdSet.add(tsk.WhoId);
                taskByContactIdMap.put(tsk, tsk.WhoId);
            }            
        }
                

        Map<Id, Contact> contactByIdMap = new Map<Id, Contact>();
        
        for(Contact cnt : [SELECT Id, Name, Phone, MobilePhone, Title, Email FROM Contact WHERE Id IN :contactIdSet]){
            contactByIdMap.put(cnt.Id, cnt);
        }
        
        Map<Task, Contact> taskByContactMap = new Map<Task, Contact>();
        for(Task tsk : taskList){
            taskByContactMap.put(tsk, contactByIdMap.get(taskByContactIdMap.get(tsk)));       
            
        }

Thanks!
This was selected as the best answer
Rana CracksRana Cracks
Thank you so much for this information. Rana Cracks (https://ranacracks.com)