File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes how to order numbers? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "how to order numbers?" Watch "how to order numbers?" New topic

how to order numbers?

jenny wang

Joined: Feb 23, 2001
Posts: 27
I have a question regarding utility.
I get bunch of numbers and I want to order these numbers.
When I use TreeSet. It works like this way:
[0.35, 1.45, 23.34, 34.22, 5.89, 9. 29]
but I want they look like:
[0.35, 1.45, 5.89, 9.29, 23.34, 34.22]
Then I try to use TreeMap. But since TreeMap needs a pair-key and value. I only have a group of numbers and there is possibility that numbers can be same. so numbers can't be key in the TreeMap.
It seems a very simple problem. But I just couldn't find a appropriate utility which can easily solve this problem.
Thanks for any suggestion!

Frank Carver

Joined: Jan 07, 1999
Posts: 6920
Do you need these numbers to be sorted all the time, or do you just need to sort them once (or occasionally) after they have been generated?
If you only need them to be sorted occasionally, then you might as well just add them to a list as they are received or generated, and then use one of the general purpose sort routines to sort them once they have all been added. Look at Arrays.sort(), for example.
If you need the values to be in the right order all the time, TreeSet would normally be the automatic choice for this kind of thing. Looking at your output, it looks as if you have added your numbers to the set in the form of Strings. If you add them as Floats or Doubles, the sort order should be correct, although you may get representation errors which need rounding. If you know exactly how many decimal places you will need, then multiplying and storing Integers or Longs in the set may be a better choice.
The one thing that worries me about this is your casual manetion that the numbers may not be unique. Both TreeSet and TreeMap require that their elements are unique. In fact, all Sets and Maps do. If you need to keep track of how duplicated entries, the usual trick is to use a TreeMap, with the number as the key and a count of how many duplicates as the value.
Has any of this helped?

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
maha anna
Ranch Hand

Joined: Jan 31, 2000
Posts: 1467
A sample code could be

maha anna
jenny wang

Joined: Feb 23, 2001
Posts: 27
Thanks so much!
Your guys are so helpful! It solves my problem.
I agree. Here's the link:
subject: how to order numbers?