Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > Natural sorting order for alphanumeric fields

Reply
Thread Tools

Natural sorting order for alphanumeric fields

 
 
Paul
Guest
Posts: n/a
 
      09-14-2004
I have a field that contains both numeric and alphanumeric entries, so
e.g. when I do an 'order by' in sql I would get the following order

1.2
1.25
1.3
3
50
6
ALMERA
FOCUS

But in this case , the 6 should be above the 50, but the order by
looks at the first digit only.

To get around this, I tried two implemetations of the comparator class
that I found on the web
http://pierre-luc.paour.9online.fr/N...omparator.java and
http://www.davekoelle.com/alphanum.jsp. These seemed to work well
EXCEPT for the cases containing decimal points
i.e. in the following order
1.2
1.3
1.25

Does anyone know of a sort that gets around this problem.
 
Reply With Quote
 
 
 
 
Rogan Dawes
Guest
Posts: n/a
 
      09-14-2004
Paul wrote:

> I have a field that contains both numeric and alphanumeric entries, so
> e.g. when I do an 'order by' in sql I would get the following order
>
> 1.2
> 1.25
> 1.3
> 3
> 50
> 6
> ALMERA
> FOCUS
>
> But in this case , the 6 should be above the 50, but the order by
> looks at the first digit only.
>
> To get around this, I tried two implemetations of the comparator class
> that I found on the web
> http://pierre-luc.paour.9online.fr/N...omparator.java and
> http://www.davekoelle.com/alphanum.jsp. These seemed to work well
> EXCEPT for the cases containing decimal points
> i.e. in the following order
> 1.2
> 1.3
> 1.25
>
> Does anyone know of a sort that gets around this problem.


How about something like:

public class Sorter implements Comparator {

int compare(Object o1, Object o2) {

if (o1 instanceof Number && o2 instanceof Number) {
return ((Number)o1).compareTo(o2);
} else {
return o1.toString().compareTo(o2.toString());
}

}

}

This assumes that your objects are the right type. If they are not, you
need to determine whether they are numbers or not, before comparing them.

Rogan
--
Rogan Dawes

*ALL* messages to http://www.velocityreviews.com/forums/(E-Mail Removed) will be dropped, and added
to my blacklist. Please respond to "nntp AT dawes DOT za DOT net"
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
alphanumeric sorting java_jazzy Javascript 2 05-29-2006 12:39 PM
Sorting alphanumeric Bob Javascript 12 12-11-2004 08:13 AM
Natural string sorting sks Java 6 06-18-2004 04:49 PM
Combined natural and unnatural list sorting Derek Basch Python 3 06-17-2004 02:42 AM
Code snippet: Natural string sorting C. Barnes Python 1 06-09-2004 05:27 PM



Advertisments