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?
Attribution to: Prady
Possible Suggestion/Solution #1
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);
Attribution to: techtrekker
Possible Suggestion/Solution #2
One can use Map.containsKey() to check and initialise a list as indicated, or alternate way could be like this [matter of taste ;)]
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 ]) {
List<Entity__c> entitiesForKey = mapProductEntity.get(et.Product__c);
if (entitiesForKey == null) {
entitiesForKey = new List<Entity__c>();
mapProductEntity.put(et.Product__c, entitiesForKey);
}
entitiesForKey.add(new Entity__c( field__c = et.field1__c,product__c = et.product__c, field2__c = et.value__c ));
}
Attribution to: Abhinav Gupta
Possible Suggestion/Solution #3
Depending on how your relationships are structured, I would suggest using a nested SOQL statement - so something like:
Map<id,List<Entity__c>> mapProductEntity = new Map<id,List<Entity__c>>();
for (Product2 p: [SELECT Id, Name, (Select Name,Field1__c, Field2__c FROM Entity__r) FROM Product2 WHERE ID IN : Items ORDER BY Name ]) {
mapProductEntity.put(p.Id, p.Entity__r);
}
Attribution to: BritishBoyinDC
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/4137