Natural string sorting

S

sks

Anyone got any advice on how to get a list of String's to sort 'naturally'.
What I mean is, take this 'sorted' list of 'hard drive capacities':

120GB
160GB
200GB
20GB
250GB
40GB
80GB

Obviously to a human, it would be sorted as such

20GB
40GB
80GB
120GB
160GB
200GB
250GB
 
J

Jan Schaefer

sks said:
Anyone got any advice on how to get a list of String's to sort 'naturally'.
What I mean is, take this 'sorted' list of 'hard drive capacities':
Obviously to a human, it would be sorted as such

20GB
40GB
80GB

The only solution that comes to my mind is to parse the Strings an cast
the numbers to Integer for sorting.

Just my two eurocents,

Jan
 
V

VisionSet

sks said:
Anyone got any advice on how to get a list of String's to sort 'naturally'.
What I mean is, take this 'sorted' list of 'hard drive capacities':

120GB
160GB
200GB
20GB
250GB
40GB
80GB

Obviously to a human, it would be sorted as such

20GB
40GB
80GB
120GB
160GB
200GB
250GB


Write a java.util.Comparator and offer this to a sort method such as

java.util.Collections.sort(List list, Comparator c);

ie

class MyStringSorter implements Comparator {

public int compare(Object o1, Object o2) {
// your comparison code
}
public boolean equals(Object obj) {
// your comparison code
}

}
 
M

Michael Borgwardt

sks said:
Anyone got any advice on how to get a list of String's to sort 'naturally'.
What I mean is, take this 'sorted' list of 'hard drive capacities':

120GB
160GB
200GB
20GB
250GB
40GB
80GB

Obviously to a human, it would be sorted as such

Obvious only if you interpret it as *numbers* (not strings) with
some irrelevant suffix. Make the computer interpret it like that
as well and you're there.
 
E

Eric Sosman

sks said:
Anyone got any advice on how to get a list of String's to sort 'naturally'.
What I mean is, take this 'sorted' list of 'hard drive capacities':

120GB
160GB
200GB
20GB
250GB
40GB
80GB

Obviously to a human, it would be sorted as such

20GB
40GB
80GB
120GB
160GB
200GB
250GB

http://sourcefrog.net/projects/natsort/

Haven't used it myself, but the site has links to
implementations in three or four languages, including
Java.
 
R

Roedy Green

20GB
40GB
80GB
120GB
160GB
200GB
250GB

Two techniques:

1. extract the numbers as ints first and put them as fields in your
records. Then sort on that.

2. slower, but requires no extra field. Scan the fields to see if
they can be converted to numbers. If so, use a numeric sort. Your
compare method extracts the number for each compare.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top