4

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?

1
  • i would ask, why you need sorting dictionary? you probably using wrong data structure for that. Commented Mar 17, 2012 at 7:19

4 Answers 4

6

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.

1
  • Oh, I wasn't aware of method asSortedCollection:. Clearly, it is more readable. Thanks! PS: It should be > instead of < Commented Mar 16, 2012 at 18:44
2

If you're using VisualWorks, you can take advantage of SortFunction and Symbol>>value behavior to reduce all of that down to

(aDictionary associations sort: #value ascending) collect: #key
0
2

If you can use Grease (eg, when using Seaside), you can probably use its GROrderedMultiMap. It is intended for small dictionaries with probably multiple values per key.

On a second note, probably you can swap key and value, and just send #asSortedCollection, like this:

(Dictionary newFrom: { 2 -> 'b' . 1-> 'a' }) 
    asSortedCollection "-->  a SortedCollection('a' 'b')"

(Tested in Squeak and Pharo)

1
  • Or just: (Dictionary newFrom: { 2 -> 'b' . 1-> 'a' }) sorted
    – aka.nice
    Commented Jun 2, 2014 at 19:25
1

Got it:

^ ((SortedCollection sortBlock: 
   [:association :otherAssociation | association value > otherAssociation value])
   addAll: theDictionary associations;
   yourself) collect: [:association | association key]
0

Not the answer you're looking for? Browse other questions tagged or ask your own question.