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?


2 Answers 2

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

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


I wrote a blog on this: http://www.bland.io/post/constructing-a-map-from-a-list

  • 12
    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, 2014 at 16:27

You must log in to answer this question.

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