I have an ArrayList that contains,
[0] = "1"
[1] = "10"
[2] = "2"
[3] = "15"
[4] = "17"
[5] = "5"
[6] = "6"
[7] = "27"
[8] = "8"
[9] = "9"
Now i need to sort the array list such that it becomes,
[0] = "1"
[1] = "2"
[2] = "5"
[3] = "6"
[4] = "8"
[5] = "9"
[6] = "10"
[7] = "15"
[8] = "17"
[9] = "27"
At last i will be getting the values from ArrayList and using them as 'int' values. How can i do this? Or shall i convert them to int at first and then sort them.?
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
It is not possible to obtain sorted array.
If you can be sure the list contains only strings that can be transformed to integers, then with the IEnumerable<T>.OrderBy
extension method, try this:
var sortedList = list.OrderBy(item => int.Parse(item));
If you're using an ArrayList
instead of a List<string>
(boo!), you'll need to Cast
first:
var sortedList = list.Cast<string>().OrderBy(item => int.Parse(item));
You can also define your own comparer as JaredPar noted, but IMO that's a lot of work for something that's already implemented. However, it's more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With