function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Kool_RudKool_Rud 

nested looping of a map

Any help is appreciated, even if it is try searching for this or puesdo code. Just looking for some direction here. Thanks, Newbie.

 

I am not sure if i am asking this question correctly or googling it correctly either.

I am trying to do someting as follows but don't want to use nested for loops, unless that is the only way - which in any case I am still not recieving my expected results.

 

For(custObj_A var1 : map1.values()){
 For(custObj_B var2: map2.values(){
   if(var2.field == var1.field){
      new custObj_D from the values of both custObj_A and custObj_B; 

 

 

The problem I am having is that custObj_B has multiple matches to 1 CustObj_A.

 

I am expecting:

1 - 1

1 - 2

2 - 1

2 - 2

 

but receiving:

1 - 1

2 - 1

 

What am I missing here?

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Avidev9Avidev9

Well map are said to be unordered list, i.e they dont maintain the sequence. So if your code depends on the sequence I guess it will fail.

 

All Answers

ryanjuptonryanjupton

Here's a hint. With what you have, we'll loop through every object in custObj_B for each object in custObj_A. That sounds like it isn't what you want. If you would more specific help please post the code that is giving you trouble and see if one of the knowledgeable people around here could help.

Avidev9Avidev9

Well map are said to be unordered list, i.e they dont maintain the sequence. So if your code depends on the sequence I guess it will fail.

 

This was selected as the best answer
Kool_RudKool_Rud
I finally got it to work by building a solution that didn't rely on sequence but instead utilized conditional statements to build what I needed. Thanks btw, sometimes I overlook the simplest of things.
Eli Flores, SFDC DevEli Flores, SFDC Dev

You can also simplify it a bit by mapping on var1.field and var2.field then do something like map<fieldtype field1, list<var2 object>>

 

for ( fieldtype field: map1.keyset()){

for ( var2 var2 :  map1.get(field)){

for ( var1 var1: map2.get(field)){

   populate custom object

}

}

}

 

 

if you're dealing witha  relatively nsmall list, it might not be worth it. But if you are dealing with relatively large lists, this will trim down the number of script statements that are required to fulfill the objective.