ShowAll Questionssorted byDate Posted

# 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 >();
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
BALAJI CH
Hi Shaik,
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:

```List < string > testList = new List < string >();
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 (06 hours, 12 hours, 24 hours, 48 hours, 72 hours, 720 hours)```

```List < integer > testList = new List < integer >();
system.debug('before sort is '+testList); // before sort is (12, 48, 24, 6, 72, 720)
testList.sort();
system.debug('after sort is '+testList); // after sort is (6, 12, 24, 48, 72, 720)```

Let me know if that helps you.

Best Regards,
BALAJI​

BALAJI CH
Hi Shaik,
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:

```List < string > testList = new List < string >();
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 (06 hours, 12 hours, 24 hours, 48 hours, 72 hours, 720 hours)```

```List < integer > testList = new List < integer >();
system.debug('before sort is '+testList); // before sort is (12, 48, 24, 6, 72, 720)
testList.sort();
system.debug('after sort is '+testList); // after sort is (6, 12, 24, 48, 72, 720)```

Let me know if that helps you.

Best Regards,
BALAJI​
This was selected as the best answer
Amit Chaudhary 8
Hi Shaik,

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
```List <integer> testList = new List <integer>();