19

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

Sample code:

Set<String> priceBooksNames = new Set<String>(); priceBooksNames.add('LN-200'); priceBooksNames.add('LN-100'); 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?

2 Answers 2

33

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); } 
2
  • 1
    Agree, here is the doc: Maps from SObject Arrays Commented Sep 10, 2013 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. Commented Dec 3, 2013 at 19:59
-1
List<string> strList = new list<string>(); strList.add('LN-200'); strList.add('LN-100'); system.debug(strList); // for Testing purpose PriceBook2 pbk = new PriceBook2(); pbk.name='LN-200'; insert pbk; map<string, PriceBook2 > pbkMap= new map<string, PriceBook2 >(); list<PriceBook2 > pbkList = [select id, name from PriceBook2 ]; for (PriceBook2 pbk: pbkList ) { pbkMap.put(pbk.name, pbk); } system.debug(pbkMap.get('LN-200')); //returns the correct pricebook data 
1
  • Yes, but the existing answer from 9 years ago is more to the point and provides an explanation. The explanation is as important as the solution itself. Commented Dec 25, 2022 at 12:10

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.