1

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);
        }
      }
9

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.

| improve this answer | |
  • 2
    It could be even cleaner if you remove the inner loop and do finalListOpps.addAll(oppList) to add all of the inner list elements at once. – John Towers Feb 28 '17 at 19:40
  • @JohnTowers Indeed. I was just making my edit when you commented. – Derek F Feb 28 '17 at 19:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.