Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Java in General and the fly likes Sorting ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting ArrayList" Watch "Sorting ArrayList" New topic
Author

Sorting ArrayList

Stuart Chambers
Greenhorn

Joined: Feb 01, 2004
Posts: 7
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

Joined: Feb 01, 2004
Posts: 7
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

Joined: Feb 07, 2005
Posts: 2367
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

Joined: Jan 30, 2000
Posts: 18671
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...


"I'm not back." - Bill Harding, Twister
Stuart Chambers
Greenhorn

Joined: Feb 01, 2004
Posts: 7
Thank you both Keith and Jim. This is exactly what I was after.

Stu...
Mahadevan Gorti SS
Greenhorn

Joined: Jan 31, 2006
Posts: 18
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
 
subject: Sorting ArrayList
 
Similar Threads
Merging Multiple Lists
collections
How many String objects ... ?!
overriding/poly morphic question
Generic Subtyping - Method Call with Subtype