I have a List<List<Opportunity>> totalMpRecords
I want to be able to extract all the Opportunties in each of those Lists and put them in one main List.
This seems pretty straightforward, yet I cannot figure out how to do this efficiently. The following does not compile:
//List<List <Opportunity>> totalMpRecords
//List<Opportunity> finalListOpps
for(Opportunity opp : totalMpRecords){
for(Opportunity innerList : opp.Opportunities){
finalListOpps.add(innerList);
}
}
Best Answer
You're close to the solution.
The thing that you're getting caught on is that the outer loop isn't iterating over a single
Opportunity
, but rather aList<Opportunity>
+edit:
A slightly different way to approach this, while eliminating the inner loop from your code would be to use
List.addAll()
, which can take a list, and add all of its elements to another list.If we could dig into the implementation of
addAll()
, it'd probably contain afor
loop of its own, so there's not likely any noticeable performance difference between the two. Dealing with nested structures is often an O(n^2) affair.