Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!

# how to order numbers?

jenny wang
Greenhorn
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!

Jenny

Frank Carver
Sheriff
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?

maha anna
Ranch Hand
Posts: 1467
A sample code could be

regds
maha anna

jenny wang
Greenhorn
Posts: 27
Thanks so much!