[SalesForce] Iterate through Map with a List of sObjects

After resolving my issue posted here, I was finally able to get a Map<Id,List<Quote>> variable like I needed, but now I can't seem to iterate through the variable. I have tried things like this:

for(Contact cid : quotes.keyset()){
    System.debug(quotes.get(cid));
}

Results: [ERROR] Incompatible key type SOBJECT:Contact for MAP>

AND

for(List<Quote> q : quotes.values()){
    System.debug(q);
}

Results: System.QueryException: List has more than 1 row for assignment to SObject

Best Answer

Your key in the map is of type Id, so your first for loop should be on Id:

for (Id recordId : quotes.keySet())
{}

Then your value for each of the keys (IDs) is a list of quotes, meaning the second for loop will be on the Quote object:

for (Id recordId : quotes.keySet())
{
    for (Quote quoteRecord : quotes.get(recordId))
    {
        // do something
    }
}

Alternatively if you want to go through all the quotes regardless of the IDs, you can do this:

for (List <Quote> quoteList : quotes.values())
{
    for (Quote quoteRecord : quoteList)
    {
        // do something
    }
}
Related Topic