I'm trying create a Map using a name field as key.

Sample code:

Set<String> priceBooksNames = new Set<String>();

Map<string,PriceBook2> priceBooks = new Map<string,PriceBook2>([SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]);
system.debug(priceBooks.get('LN-100')); //this is returning NULL

I can see on console that setId on map is not getting the name field value.

VARIABLE_ASSIGNMENT [5]|priceBooks|{"serId":1,"value":{"01sb0000000hiqQAAQ":{"serId":2,"value":{"Name":"LN-100 ADULTOS","Id":"01sb0000000hiqQAAQ"}},"01sb0000000hiqGAAQ":{"serId":3,"value":{"Name":"LN-200 EMPRESAS","Id":"01sb0000000hiqGAAQ"}}}}

What I'm going wrong?


As far as I'm aware the map constructor only supports ID-->Sobject.

If you want a different key, then you have to build the map yourself.

Map<String, PriceBook2> priceBooks = new Map<String, PriceBook2>();
for (Pricebook2 p : [SELECT name,id FROM PriceBook2 WHERE name=:priceBooksNames ]) {
   priceBooks.put(p.name, p);
  • 1
    Agree, here is the doc: Maps from SObject Arrays – Sergej Utko Sep 10 '13 at 11:43
  • For a more general sObject the name may not be unique and you would need to add extra checks to see if it is already in the Map keys. – Daniel Ballinger Dec 3 '13 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.