[SalesForce] Traverse through List> (multi-dimension)

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 a List<Opportunity>

// Outer loop on a List<List<Opportunity>> gets you one level in, resulting in
//   a List<Opportunity>
for(List<Opportunity> oppList : totalMpRecords){
    // Inner loop works on each List<Opportunity>, giving you the individual
    //   Opportunities.
    for(Opportunity innerList : oppList){
      finalListOpps.add(innerList);
    }
  }

+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.

for(List<Opportunity> oppList : totalMpRecords){
    finalListOpps.addAll(oppList);
}

If we could dig into the implementation of addAll(), it'd probably contain a for 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.

Related Topic