Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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

share|improve this question
add comment

2 Answers 2

up vote 9 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
add comment

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

historyMap.putAll(historyList);

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

share|improve this answer
1  
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 at 16:27
add comment

Your Answer

 
discard

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.