Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a Dictionary by values in Smalltalk?

I've got a Dictionary like this:

a PluggableDictionary(
    Rankable1->8.5
    Rankable2->9.0
)

I need just an OrderedCollection with the Rankable objects in descending order:

a OrderedCollection(
    Rankable2
    Rankable1
)

I noticed it is easy to sort by keys, but I found it a bit more difficult to sort by values. What is the smalltalk way of doing this?

like image 439
Mosty Mostacho Avatar asked Dec 21 '22 00:12

Mosty Mostacho


1 Answers

If you need one shot sorted collection in noncritical loop you might use something like this (uses pharo syntax to initialize example dictionary):

pd := PluggableDictionary newFromPairs: { 'a' . 2 . 'b' . 1 . 'c' . 3} . 

(pd associations asSortedCollection: [:x :y | x value < y value]) 
            collect: [:assoc | assoc key].

If you would need it more often, than you might consider introducing your own class that will keep this collection calculated.

like image 90
Davorin Ruševljan Avatar answered Dec 23 '22 14:12

Davorin Ruševljan