• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting a List of String Values  RSS feed

 
Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bartender
Posts: 1638
IntelliJ IDE Java MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!