[SalesForce] How to define a map with id and list of records of an object

I have a custom object called entity_c, this has a field called product which is a lookup to product. There could be many records in entity_c for a particular product.

I need to store it in a map with productId as the key and all the records for that product in a list.

Here is what i have till now

  Map<id,List<Entity__c>> mapProductEntity = new    Map<id,List<Entity__c>>();
  for(Entity__c et : [SELECT name,Field1__c, Product__c, Field2__c FROM Entity__c WHERE Product__c IN : Items ORDER BY Product__c ]{
        if (mapProductEntity.containsKey(et.Product__c)){
            mapProductEntity.get(et.Product__c).add(new Entity__c(    field__c = et.field1__c,product__c = et.product__c, field2__c = et.value__c ));
        }
        else{
      // Not sure how to add it for first time      
             //mapProductEntity.put(et.Product__c, lsEntit.add(new Entitlement__c(   field1__c = et.field1__c,product__c = et.product__c, field2__c = et.value__c )));
        }

Is this a right approach? Is there a simpler way to do it?

Best Answer

Yes it seems alright to do it like you have, To add for the first time

mapProductEntity.put(et.Product__c, new List <Entitlement__c> { et });

Even where you're adding it above you don't need to reconstruct Entitlement__c as that is already your loop variable.

So even above you can use

if (mapProductEntity.containsKey(et.Product__c))
            {
mapProductEntity.get(et.Product__c). add(et);
Related Topic