File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Sorting a List of String Values Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Sorting a List of String Values" Watch "Sorting a List of String Values" New topic
Author

Sorting a List of String Values

Ramesh Etta
Ranch Hand

Joined: Sep 18, 2007
Posts: 46
Hi,

I am new to java. I have taken a List object and add the String values like Week01,Week02, ........... upto Week51. When we sort this list object usint Collections.sort(list object); I get the output something like this Week01,week10,Week11,.......Week02,Week20,Week21.....

But i want the sort order like Week01,Week02...... Week09,Week10,......

Can any one come with solution,of how to sort this order the way i like above.

Thanks in advance.
Nitesh Kant
Bartender

Joined: Feb 25, 2007
Posts: 1638

Not an advanced question.
Anyways answering your question.
The reason why you are getting the order is that if you do not specify a Comparator then the natural ordering (in your case natural-order for String i.e. alphabetical) will be used to sort.

Have you seen the method Collections.sort(List list, Comparator c)?
This method will come to your rescue
Write a Comparator that can compare two string of the way you expect i.e. remove the prefix Week, parse the remaining number(Integer.parseInt()) i.e. Integer and return the compareTo result for integer.

Did not want to write the code here, so that you can do some R&D and find it yourself, following this javaranch policy


apigee, a better way to API!
 
 
subject: Sorting a List of String Values
 
Similar Threads
Bubble Sort Set using Comparator
generic wildcard and the API for Collections
sorting the list based on another list
how to sort this list ?
Sorting two ArrayLists, one dependent on the other