24

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?

Thanks

2 Answers 2

53
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);
0
17

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

historyMap.putAll(historyList);
1
  • 13
    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
    Commented 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 .