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
SalesRedSalesRed 

How To Get a "Sub Map" starting at a position within a Map

Hi,

 

Do you know if it is possible to get values from a map starting at a particular position in a map, until the end of the map?

 

Kind of like a substring function but instead to create a new submap.

 

Any suggestions are welcome.

 

Thanks in advance.

Best Answer chosen by Admin (Salesforce Developers) 
netspidernetspider

Yes no prob just do something like

 

String[] alist= new String[]{};

alist.addall(map.keyset());

for (integer i=5;i<=map.size();i++)

map.get(alist[i]);//do something with what is returned of course

All Answers

Shailesh DeshpandeShailesh Deshpande
I wonder why would you have such a requirement when you can simply access any element using the map.get(key) method.
netspidernetspider

You could to get the 5th element

 

String[] alist= new String[]{};

alist.addall(map.keyset());

map.get(alist[5]);

SalesRedSalesRed

Hi Guys,  Thanks for your help.

 

I would require all elements in the map from the starting position (of 5 for eaxmple) instead of just getting the one element. Is there a way of doing this without looping through the map and creating a new map that way?:

 

No worries if not but thought I'd check all the same.

netspidernetspider

Yes no prob just do something like

 

String[] alist= new String[]{};

alist.addall(map.keyset());

for (integer i=5;i<=map.size();i++)

map.get(alist[i]);//do something with what is returned of course

This was selected as the best answer
netspidernetspider

 

If you wouldn't mid to mark my answer as Best Answer, it helps me as well, if the code helps you

SalesRedSalesRed

Hi netspider.  

 

Is a for loop required & to then add the values one by one?  This is what I was querying, if there's an alternative (similar to a substring for a String type). If not then I guess a for loop is the best way.

 

Thanks.

sfdcfoxsfdcfox

But keep in mind that a map is an unordered list of values, which means that the order they are added is not necessarily their actual order (nor in any other order). Only the collection type List has a defined order to its elements. But if you have an ordered list of keys, you can then use the for loop suggested above to retrieve just the selected subelements. I mention this only because the way elements are defined in a map may change in future versions, so any code you are writing should not depend on a specific ordering behavior of maps as they exist today.