Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting ArrayList

 
Stuart Chambers
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have an ArrayList of data which looks as follows:

"A"
"H"
"L1"
"L100"
"L11"
"L2"
"L3"
"X"

I would like to sort this ArrayList so that the numerical values are sorted correctly, such that the list looks like:

"A"
"H"
"L1"
"L2"
"L3"
"L11"
"L100"
"X"

Any suggestions would be greatly appreciated.
Stu...
 
Stuart Chambers
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I forgot to mention I tried using Collections.sort, however this sorts the strings in the same fashion as stated in the first list.
Stu...
 
Keith Lynn
Ranch Hand
Posts: 2399
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is one way I've come up with.

Basically the idea is to use a Comparator. In the Comparator, the character portion of the Strings are seperated from the numeric portion. Then as Strings, the numeric portions are left padded with 0s to be of equal length. The Strings are then put back together and compared.

So, for example, when comparing L2 and L100, the Strings would become L002 and L100.

This code works under the premise that each String in the ArrayList will be composed of one or more characters followed by one or more digits.



[ March 23, 2006: Message edited by: Keith Lynn ]
[ March 23, 2006: Message edited by: Keith Lynn ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I recommend creating a java.util.Comparator (to be used in Collections.sort(List, Comparator)) which defines the sort order you need. Probably you will want to separate the first letter of each string from the rest of the strings. If the first letters are equal, convert the remaining parts of the strings to numbers using Integer.parseInt(), and use those values to determine which value comes first. Hope that helps...
 
Stuart Chambers
Greenhorn
Posts: 7
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you both Keith and Jim. This is exactly what I was after.

Stu...
 
Mahadevan Gorti SS
Greenhorn
Posts: 18
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stu,
Hope this link will take care of all possible future cases & conbinations

http://pierre-luc.paour.9online.fr/NaturalOrderComparator.java
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic