Search code examples
dictionarysmalltalkpharo

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?


Solution

  • 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.