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
Arjun y 7Arjun y 7 

How to sort list of strings

Hi All,

Could any one tell me how to sort the below list of strings?

Input : List<String> strList = new List<String>{'1_4','1_2','1_8','2_3'};

Output Should display as : 1_2,1_4,1_8,2_3

Thanks
Arjun

 
JeffreyStevensJeffreyStevens
strList.sort();

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_collections_lists_sorting.htm

 
Kevin CrossKevin Cross
If the strings are more complex (e.g., 1_10 and 10_1), then you may need to create a custom comparator or use a utility class that takes a string array|list and returns sorted list.  In this comparator, you could split the strings on the '_' then convert each side of the string into an integer.  Then compare the integers for sorting purposes.  In other words, compare first integers first then second if the first set are equal.