[SalesForce] Apex Maps and SOQL queries

I am trying to put the values from my SOQL query into a map.

This is my example:
I have a custom object "disease__c" and a custom object "patient__c". They are a master-detail relationship where disease__c is the master object.

My query is like this:

SELECT Email__c, diseaseR__r.Name FROM patient__c;

Like this I will get all the email addresses of patients linked to a disease.

So, what I now need to do is to send an email to all patients that have a certain disease, i.e. all patients that have Rubella will receive an email saying "You have Rubella" (btw – I am learning Force.com development, this is not a real application ;))

This is what I have done:

Map<String, String> email_disease_pairs = new Map <String, String> ();
email_disease_pairs = [SELECT Email__c, diseaseR__r.Name FROM patient__c];

Unfortunately I get the following error:

Save error: list must have exactly 1 type argument

I am not sure what this means?

Any help would be appreciated!

Best Answer

Check this:

Map<Id, Set<String>> emailDiseaseMap = new Map <Id, Set<String>> ();

for(Patient__c patient : [  SELECT Email__c, Diseaser__c 
                            FROM Patient__c]){
    if(!emailDiseaseMap.containsKey(patient.Diseaser__c)){
        emailDiseaseMap.put(patient.Diseaser__c , new Set<String>());
    }
    emailDiseaseMap.get(patient.Diseaser__c).add(patient.Email__c);
}

I've make some changes in your code:

Map type is change to Map<Id, Set<String>> because - Id of parent is unique value and id could happen that you have 2 record with same name - and I don't think you want this. I also used Set<String> to keep all unique email adresses for paarent.

Related Topic