Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a list of OpportunityHistories. I want to convert to a Map, where the ID is the OpportunityID (not the OpportunityHistory) and the value to be an OpportunityHistory object.

I know for a fact I will only have one OpportunityHistory object per Opportunity ID so I am ok there.

Any tips?


share|improve this question
up vote 12 down vote accepted
Map<Id, OpportunityHistory> historyMap = new Map<Id, OpportunityHistory>();
for(OpportunityHistory oh : historyList)
     historyMap.put(oh.OpportunityId, oh);

this way you will only have one opportunityHistory per opportunityId of course

if you would want to add the opportunityHistory with the opportunityHistoryId as key and the opportunityHistory object as value.

you could simply do:

Map<Id, OpportunityHistory> historyMap = new Map<Id, OpportunityHistory>(historyList);
share|improve this answer

Using .putAll() will convert a list of SObjects to a map with the record.Id as the key


I wrote a blog on this:

share|improve this answer
This doesn't address the issue raised in the question. It specifically notes that the ID values of the items in the list should not be the keys for the map. Additionally, you can use the Map constructor itself rather than using putAll() as new Map<Id, sObject>(List<sObject>). – Mark Pond Feb 11 '14 at 16:27

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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