[SalesForce] Comparing Two Lists of Related Objects

I have two custom objects, Question__c and Response__c. There is a lookup field named Related_Question__c on the Response__c object to relate the two. In my VF controller I have two Lists, one for each object. My objective is to find all records in the Question List that do not have a match in the Response List (ie questions that haven't been answered yet).

I believe I need to use a map for this but am unsure of exactly how to accomplish this. Any advice would be appreciated. Thanks in advance.

Here's what I have so far to build the two Lists:

List <Question__c> questions = [select Id, Name From Question__c];
List <Response__c> questionResponses = [select Id, Name, Related_Question__c From Response__c Where Related_Question__c IN: questions};

Best Answer

Can you try something like this ?

List<Id> l = new List<Id>();
Map<Id,Response__c> qr = new Map<Id,Response__c>();
for(Response__c r : questionResponses)
{

    qr.put(r.Related_Question__r.Id,r);
}
for(Question__c q :  questions)
{

  if(qr.get(q.Id) == null)
 {
      l.add(q.Id);    
}

}
System.debug('~~~ Non matching Ids '+ l);
Related Topic