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
alibzafaralibzafar 

Looping through a Map

 

I want to do similar thing below , but using a Map, is there any similar funcationality available?

 

The list or set iteration for loop iterates over all the elements in a list or set. Its syntax is:


for (variable : list_or_set) {
code_block
}

 

where variable must be of the same primitive or sObject type as list_or_set. When executing this type of for loop, the Apex runtime engine assigns variable to each element in list_or_set, and runs the code_block for each value. For example, the following code outputs the numbers 1 - 10 to the debug log:

 

Integer[] myInts = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (Integer i : myInts) {
System.debug('test test');

}

 

 

I tried this but got error, 

 

public Map<Integer, myClass>  myItems;

 

for (myClass item : this.myItems){}

 

Save error: Loop must iterate over a collection type: MAP<Integer,myClass> :( 

 

Can anyone help on this?

 

Thanks 

 

Best Answer chosen by Admin (Salesforce Developers) 
mohimohi

for(integer varI : myItems.keyset())

{

 

variable=myItems.get(varl);

Logic....

 

}

 

OR

for (myClass item : myItems.values()){}

 

 

 

please mark as accepted if its your solution

All Answers

mohimohi

for(integer varI : myItems.keyset())

{

 

variable=myItems.get(varl);

Logic....

 

}

 

OR

for (myClass item : myItems.values()){}

 

 

 

please mark as accepted if its your solution

This was selected as the best answer
alibzafaralibzafar

Yes !

 

for (myClass item : myItems.values()){}   works :-) 

 

Thanks 

David Roberts 4David Roberts 4
Thanks, Mohi - saved me hours.