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?


  • pjcarly

    pjcarly Correct answer

    9 years ago
    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);

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used