What is the quickest way to convert a list to a map?

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?



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

Source : Link , Question Author : dublintech , Answer Author : pjcarly

Leave a Comment