Apex Map using “Name” as key

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?

Answer

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);
}

Attribution
Source : Link , Question Author : Martin Borthiry , Answer Author : Doug B

Leave a Comment