地图内的Apex地图

时间:2012-03-01 18:23:27

标签: triggers salesforce apex-code

我需要在我的一个触发器中的地图中有一个地图。我知道如何在最初建立地图时记录:

Map<Id, Map<Id, Addendum__c>> addendums = new Map<Id, Map<Id, Addendum__c>>{};

但是,我实际上在为多维地图分配值时遇到了麻烦。通常我会使用.put()将值放入单维地图中。也许我仍然应该使用那个功能,但我不能为我的生活找出正确的语法。

我尝试过以下哪些不起作用:

addendums.put(addendum.Opportunity__c, addendum.Id, addendum);

addendums.put(addendum.Opportunity__c, (addendum.Id, addendum));

有谁知道怎么做?

谢谢!

3 个答案:

答案 0 :(得分:3)

使用您的示例代码会起作用,当然第二级地图只能有一个条目,如果您处的情况可能需要更多,那么下面的代码将为您解决问题:

// This line creates the map in the proper format
Map<Id,Map<Id,Addendum__c>> addendums = new Map<Id,Map<Id,Addendum__c>>{};

// This for loop goes through each addendum and first places it into a single dimension map.  
// Once that map is created, it is placed into the final multi-dimensional
for(Addendum__c addendum : [SELECT Id,Opportunity__c FROM Addendum__c WHERE Opportunity__c IN :oppBatch])
{
    if(addendums.get(addendum.Opportunity__c) == null)
    {
        addendums.put(addendum.Opportunity__c, new Map<Id, Addendum__c>{addendum.Id => addendum);
    }
    else
    {
        addendums.get(addendum.Opportunity__c).put(addendum.Id, addendum);
    }
}

正如您所看到的,这会在第一张地图上使用get()来获取我们想要添加附录的正确的二级地图。

答案 1 :(得分:2)

Josh提供的方法很好。如果您想删除一行代码,可以使用以下方法:

Map<Id, Map<Id,Addendum__c>> addendums = new Map<Id,Map<Id,Addendum__c>>();
for(Addendum__c addendum : [SELECT Id,Opportunity__c FROM Addendum__c WHERE Opportunity__c IN :oppBatch]){
    addendums.put(addendum.opportunity__c, new Map<Id, Addendum__c>{addendum.id => addendum});
}

我不知道比这更有效的方法。

答案 2 :(得分:0)

我找到了一种方法来做到这一点,虽然我不确定它是否是最有效的方法。因此,如果您有更好的解决方案,请告诉我,我会将“解决方案”转移给您。

我所做的是分配第一张地图,然后将该地图放在最终地图中。

// This line creates the map in the proper format
Map<Id,Map<Id,Addendum__c>> addendums = new Map<Id,Map<Id,Addendum__c>>{};

// This for loop goes through each addendum and first places it into a single dimension map.  
// Once that map is created, it is placed into the final multi-dimensional
for(Addendum__c addendum : [SELECT Id,Opportunity__c FROM Addendum__c WHERE Opportunity__c IN :oppBatch]){
    Map<Id,Addendum__c> thisAddendum = new Map<Id,Addendum__c>{ addendum.Id => addendum };
    addendums.put(addendum.Opportunity__c,thisAddendum);
}