4

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

2 Answers 2

12

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
    }
}
0
-3

If you want to iterate over a Map and do some logic for specific keys use this

Map<Integer, String> m= new Map<Integer, String> {1=> 'a', 2=>'b'};

Integer[] n = new Integer[]{};
for (Integer i : m.keySet())
{
    n.add(i);
}
Integer j = 0;
for (String s : m.values())
{        
    if (n[j]== 1) {  // 1 here is value of the key, you can use your value

        //DO something
        system.debug(n[j]+' '+s);    j++;
    }
}
1
  • 2
    Thanks for an example of what NOT to do. This is wrong in so many ways. Especially in the unneeded code if one was to take your approach as the iteration on the keys is complete waste
    – Eric
    Commented Nov 27, 2016 at 16:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .