[SalesForce] how to populate Map> i want to map Profit Center with a list of Employees associated to that Profit Center

I want to populate Profit Center with a list of Employees associated to that Profit Center. The code below is not allowing me to add the employees into the List and put the values into the Map.

Best Answer

You're trying to use the set as a key, which is not correct. You meant to use the Profit_Center__c Id value. Here's an optimized version that does that. Note that this code doesn't "do" anything by itself; I presume that you'll have to add additional logic that does something productive later.

public class EmployeeTriggerHelper {
  public static void checkEmployee(Employee__c[] trgNew) {
    Map<Id, List<Employee__c>> organized = new Map<Id, List<Employee__c>>();
    for(Employee__c record: trgNew) {
      organized.put(record.Profit_Center__c, new Employee__c[0]);
    }
    for(Employee__c record: [SELECT Profit_Center__c FROM Employee__c WHERE Profit_Center__c = :organized.keySet()]) {
      organized.get(record.Profit_Center__c).add(record);
    }
  }
}
Related Topic