Apex Listを使用してMapに格納する方法

環境
Salesforce

書式
Map<Id,Account>Map変数名 =new Map<Id,Account>();
for(Account Account変数名 : リスト変数名){
Map変数名.put(Account変数名.Id, Account変数名);
}
AccountのIdをkeyにして、Accountレコード自体をvalueとして対応付けています。
istをfor文で回して結果をMapに格納します。

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
//Accountレコードを取得
List<Account> accList = [Select Id,Name From Account Limit 6];
//Mapの宣言
Map<Id, Account> accountMap = new Map<Id, Account>();
//取得したAccountレコードを1件ずつ回してMapに格納
for(Account acc : accList){
accountMap.put(acc.Id, acc);
}
system.debug(accountMap);
//Accountレコードを取得 List<Account> accList = [Select Id,Name From Account Limit 6]; //Mapの宣言 Map<Id, Account> accountMap = new Map<Id, Account>(); //取得したAccountレコードを1件ずつ回してMapに格納 for(Account acc : accList){ accountMap.put(acc.Id, acc); } system.debug(accountMap);
//Accountレコードを取得
List<Account> accList = [Select Id,Name From Account Limit 6];

//Mapの宣言
Map<Id, Account> accountMap = new Map<Id, Account>();
    //取得したAccountレコードを1件ずつ回してMapに格納
    for(Account acc : accList){
        accountMap.put(acc.Id, acc);
    }

system.debug(accountMap);

 

Apex

Posted by arkgame