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
Felipe OliveiraFelipe Oliveira 

loop through map keeping the map order

hi

 

Im new to APEX and VF.

 

I'm trying to create a bread crumbs system for my pages. The idea is to add pages to map and than loop through the map and build the bread crumbs.

 

The problem Im facing is the order of the items interated over the loop is not the same of items added in the map.

 

Do you guys know how to loop and maintain the original item order?

 

this is my code

 

 breadCrumbs = new Map<String,String>{'Home'=>'/apex/Home','Build Car'=>'/apex/Build_car'};

 for (String fieldName : breadCrumbs.keySet()){
     sBreadCrumbs = sBreadCrumbs + '<a href="' + breadCrumbs.get(fieldName) + '">' + fieldName + '</a>'; 
 }

 

Any ideas how to maintain the order in the loop?

 

 

 

 

Best Answer chosen by Admin (Salesforce Developers) 
Richie DRichie D

Hi,

 

You can't... The map order is based on hash values and so not as you would hope for.

 

You would needsomething like

set<string> orderedbreadCrumbs = new set<string>{'Home','Build car'};

 Map<String,String> breadCrumbs = new Map<String,String>{'Home'=>'/apex/Home','Build Car'=>'/apex/Build_car'};
string sBreadCrumbs = '';
 for (String fieldName : orderedbreadCrumbs ){
     sBreadCrumbs = sBreadCrumbs + '<a href="' + breadCrumbs.get(fieldName) + '">' + fieldName + '</a>'; 
 }
system.debug(sBreadCrumbs);

 

 

 Sets and Lists keep their ordering intact so you can loop around that.

Good luck and welcome to Apex!

Rich.

All Answers

Richie DRichie D

Hi,

 

You can't... The map order is based on hash values and so not as you would hope for.

 

You would needsomething like

set<string> orderedbreadCrumbs = new set<string>{'Home','Build car'};

 Map<String,String> breadCrumbs = new Map<String,String>{'Home'=>'/apex/Home','Build Car'=>'/apex/Build_car'};
string sBreadCrumbs = '';
 for (String fieldName : orderedbreadCrumbs ){
     sBreadCrumbs = sBreadCrumbs + '<a href="' + breadCrumbs.get(fieldName) + '">' + fieldName + '</a>'; 
 }
system.debug(sBreadCrumbs);

 

 

 Sets and Lists keep their ordering intact so you can loop around that.

Good luck and welcome to Apex!

Rich.

This was selected as the best answer
Damien_Damien_

Sets and Lists keep their ordering intact so you can loop around that.

Only Lists keep their ordering intact.  Sets are unordered.

Richie DRichie D

Of course - you are perfectly correct Damien_

Late in the day ;(

Rich.

Damien_Damien_

All good, just don't want to steer anyone wrong :)

Felipe OliveiraFelipe Oliveira

thanks guy, it is working now using the list to order the items