• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Sorting a List of String Values

Ranch Hand
Posts: 47
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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.
Posts: 1638
IntelliJ IDE MySQL Database Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Would you turn that thing down? I'm controlling a mind here! Look ... look at the tiny ad ...
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic