You need to sign in to do that
Don't have an account?
SHAIK MOHAMMAD YASEEN
need to sort elements in list
Hi All,
below i have a piece of code where i need to sort the items correctly but sort is not happenning correctly. please help me how to achieve in this case. Thanks
List < string > testList = new List < string >();
testList.add('12 hours');
testList.add('48 hours');
testList.add('24 hours');
testList.add('6 hours');
testList.add('72 hours');
testList.add('720 hours');
system.debug('before sort is '+testList); //before sort is (12 hours, 48 hours, 24 hours, 6 hours, 72 hours, 720 hours)
testList.sort();
system.debug('after sort is '+testList); // after sort is (12 hours, 24 hours, 48 hours, 6 hours, 72 hours, 720 hours
below i have a piece of code where i need to sort the items correctly but sort is not happenning correctly. please help me how to achieve in this case. Thanks
List < string > testList = new List < string >();
testList.add('12 hours');
testList.add('48 hours');
testList.add('24 hours');
testList.add('6 hours');
testList.add('72 hours');
testList.add('720 hours');
system.debug('before sort is '+testList); //before sort is (12 hours, 48 hours, 24 hours, 6 hours, 72 hours, 720 hours)
testList.sort();
system.debug('after sort is '+testList); // after sort is (12 hours, 24 hours, 48 hours, 6 hours, 72 hours, 720 hours
This is little tricky. As you are usign List of String, for string values the Sort function checks position wise. For Example, it checks all first letter in the string. Here, 6 is considered to be greater than '1'2 or '2'4 or '4'8 since it is checking first leters initially and goes on.
You can use double digits instead single like 06 instead of 6 OR use List of integer than String. Below snippets gives expected results:
Let me know if that helps you.
Best Regards,
BALAJI
All Answers
This is little tricky. As you are usign List of String, for string values the Sort function checks position wise. For Example, it checks all first letter in the string. Here, 6 is considered to be greater than '1'2 or '2'4 or '4'8 since it is checking first leters initially and goes on.
You can use double digits instead single like 06 instead of 6 OR use List of integer than String. Below snippets gives expected results:
Let me know if that helps you.
Best Regards,
BALAJI
Even sorting is working fine. Due to char it look like not sorted to you. If you want number should be come in sorted order then add only Integer value like below for alpha numerice please add zero as well