reverse a map and sort

p paul
Greenhorn
Posts: 8
I have a map
mymap (k, new Integer(myint))

I attempted the following:

Set cnts = new TreeSet(mymap.values());
but, since map.values returns a Collectin of Objects, the ordering is non-existant.

I want my values sorted, descending.
--OR--
I want my map of key value pairs to be ordered by the values, not the keys.

fred rosenberger
lowercase baba
Bartender
Posts: 12228
36
so what is stopping you from sorting them?

p paul
Greenhorn
Posts: 8
Bubble sorts aren't fast.

mymap.put (k, new Integer(myint));....

Set cnts = new TreeSet(mymap.values());

Where do I go from here ???
I know I can always use this :
Iterator it = mymap.entrySet().iterator();
and do my own sorting, but is this how one is supposed to?

i.e. efficient solution to problem -> sort map pairs by values

fred rosenberger
lowercase baba
Bartender
Posts: 12228
36
Originally posted by p paul:
Bubble sorts aren't fast.

Bubble sorts can be extremely fast in certain cases. if the data is mostly sorted, they might actually be the fastest.

Campbell Ritchie
Sheriff
Posts: 50666
83
Originally posted by fred rosenberger:

Bubble sorts can be extremely fast in certain cases. if the data is mostly sorted, they might actually be the fastest.
Bubble sort is quite fast when you only have a few items to sort. I did some timing of bubble vs selection vs recursive merge sort about 3 years ago; allowing for quadratic complexity in bubble and selection and nlogn complexity for merge sort, I worked out that bubble and merge are about the same speed for 2^6 (64) to 2^7 (128) members in what I was sorting, but bubble would be faster for 2^5 (32) and merge faster for 2^8 (256) members.

Campbell Ritchie
Sheriff
Posts: 50666
83
Originally posted by p paul:
sort map pairs by values
Can you get all the values into an array then create a Comparator for differences between values, then sort?

Vilmantas Baranauskas
Ranch Hand
Posts: 89
Your mamap.values() are Integer objects. TreeSet sorts them. If you need different order then you can always pass Comparator implementation to the constructor.

E.g.:

Vilmantas Baranauskas
Ranch Hand
Posts: 89
Or... you may use:

SortedMap mymap = new TreeMap(new Comparator() { ... })

Then all elements will be always sorted in your initial mymap as you define.