Iterate over a Complex Map using a for loop

Its the most common use case to use a list inside map method. here I'm going to show you how to iterate a list of elements in the map using a simple for loop.

ex: Map<Integer, list<Account>> branchCodeVsAccountMap = New Map<Integer, list<Account>>();

Iterate List Inside Map

Map<String, list<Account>> branchCodeVsAccountMap = New Map<String, list<Account>>();
List<Account> acLst = [select id, name from Account limit 100];
// add account list to map
branchCodeVsAccountMap.put('accountList',acLst);
// iterate map 
for(Account ac: branchCodeVsAccountMap.get('accountList')) {
    System.debug('Account--'+ac.Name);
}

Iterate complex Map Inside Map in apex

It's not a complex. don't confuse. Now I'm going to show you Map methods to get an inner map and loop the map and inside map.

Ex: Map<Integer, Map<Integer,Account>> cityCodeVsbranchCodeVsAccountMap = New Map<Integer, Map<Integer,Account>>();

Map<Integer, Map<Integer,Account>> cityCodeVsbranchCodeVsAccountMap = New Map<Integer, Map<Integer,Account>>();
Account ac = [select id, name from Account limit 1];
cityCodeVsbranchCodeVsAccountMap.put(0001,new Map<Integer,Account>{9999 =>ac});
System.debug('cityCodeVsbranchCodeVsAccountMap--->'+cityCodeVsbranchCodeVsAccountMap);
for(Integer cityCode: cityCodeVsbranchCodeVsAccountMap.keyset()){
    // loop on branch Code
    System.debug('cityCode-->'+cityCode);
    for(Integer branchCode: cityCodeVsbranchCodeVsAccountMap.get(cityCode).keyset()){ 
        System.debug('branchCode-->'+branchCode);
        System.debug('account-->'+cityCodeVsbranchCodeVsAccountMap.get(cityCode).get(branchCode));
    }
}
One more example with little more complex. this time Map inside map then list.see below map defined.
Ex: Map<Integer, Map<Integer,list<Account>>> cityCodeVsbranchCodeVsAccountsMap = New Map<Integer, Map<Integer,list<Account>>>();

Map<Integer, Map<Integer,list<Account>>> cityCodeVsbranchCodeVsAccountsMap = New Map<Integer, Map<Integer,list<Account>>>();
List<Account> acLst = [select id, name from Account limit 100];
cityCodeVsbranchCodeVsAccountsMap.put(0001,new Map<Integer,list<Account>>{9999 =>acLst});
System.debug('cityCodeVsbranchCodeVsAccountsMap--->'+cityCodeVsbranchCodeVsAccountsMap);
for(Integer cityCode: cityCodeVsbranchCodeVsAccountsMap.keyset()){
    // loop on branch Code
    for(Integer branchCode: cityCodeVsbranchCodeVsAccountsMap.get(cityCode).keyset()){
        // now loop on accounts
        for(Account ac: cityCodeVsbranchCodeVsAccountsMap.get(cityCode).get(branchCode)){
            System.debug('ac-->'+ac);
        }
    }
}
Labels:
Map
Join the conversation