Say I have a map:

Map<Lead, Map<Date, Decimal>> 

How does Map navigation work in a scenario like this?

I would like to first search the Lead, and then search the Date, in order to ultimately find the Decimal value associated to that Lead.

  • How do you know which lead you need to get? What's your key? Id, Email, LastName, combination? Sep 8, 2015 at 2:12
  • My key is the Lead's Id. @Bachovski Sep 8, 2015 at 2:13

1 Answer 1


There are two ways to get to it. If you know the exact keys of both maps you can get straight to it:

Decimal myDecimal;
if (myMap.containsKey(leadRecord))
    myDecimal = myMap.get(leadRecord).get(dateInstance);

though this won't work nicely because your key is a lead sObject. Unless you have the same instance of the sObject you won't be able to match the key. I would rather use a lead Id, First Name or whatever combination of keys in order to make this work. So instead of Map <Lead <Map <Date, Decimal>> I would create Map <Id, Map <Date, Decimal>>. Then it's guaranteed that you'll get the matching value based on the correct Id.

Id myLeadId = '00Q100000000ABC';
Date myDate = System.today();

Decimal myDecimal;
if (myMap.containsKey(myLeadId))
    myDecimal = myMap.get(myLeadId).get(myDate);

Alternatively, you could iterate through the keys and perform checks for each entry. So in your current scenario you could do the following:

Id myLeadId = '00Q100000000ABC'; // This is the Id we're looking for
Date myDate = System.today(); // This is the Date we're looking for
Decimal myDecimal; // we'll store the matching value here (if there is one)

for (Lead leadRecord : myMap.keySet())
    if (leadRecord.Id == myLeadId)
        myDecimal = myMap.get(leadRecord.Id).get(myDate);

if (myDecimal == null)
    // we did not find any matches
  • 2
    To add to Boris's post, you should check that the Map key exists before attempting to get the date key or you could get a dereference null object error
    – Eric
    Sep 8, 2015 at 3:54
  • Yes this answer is somewhat incomplete without containsKey.
    – Adrian Larson
    Sep 8, 2015 at 15:34
  • Agreed and updated the answer. I tend to leave those nitty gritty things to the people to figure out themselves (learning the hard way makes you remember it better :)) Sep 9, 2015 at 0:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .