0
Map<string, List<Object>> finalMap = new Map<string, List<Object>>();
                    for(Map<String, Object> cus : allJSONValues){
                        for(string key : cus.keyset()){
                            if(finalMap.containsKey(key)){
                            
                                finalMap.get(key).add(cus.get(key)); 
                            }else {
                                List<Object> newObj = new List<Object>();
                                newObj.add(cus.get(key));
                                finalMap.put(key,newObj);
                            }
                        }
                    }

allJSONValues is a List<Map<String, Object>>.

Can anyone please tell me how can I optimize this and can remove double for loop from this.

1
  • Your question is an example of XY problem. Better way to ask is to state your goals and your measurable success criteria.
    – identigral
    Commented Aug 3, 2022 at 16:22

1 Answer 1

1

Generally speaking, you can't.

If you have a nested collection like a List<List<Object>> or Map<String, Map<String, Object>>, using a nested loop is the sensible way to get access to the innermost values.

Nested loops in and of themselves are not inherently evil. They're only really bad when you have something that checks every element in one collection against every element in another collection, e.g.

// This is an example of a "bad" nested loop
// Don't use this in a real class
for(Account a :accountList){
    for(Contact cont :contactList){
        if(cont.AccountId == a.Id){
            // do work
        }
    }
}

Since your loop is not like the bad example above, it is fine. The nested loop you have will only iterate as few times as possible.

You must log in to answer this question.

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