How to sort a dictionary by values ​​in Smalltalk?

I have a dictionary like this:

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

I only need an OrderedCollection with Rankable objects in descending order:

 a OrderedCollection( Rankable2 Rankable1 ) 

I noticed that sorting by keys is easy, but it was difficult for me to sort by values. What is this little way to do this?

+4
source share
4 answers

If you need one sorted collection with one shot in a non-critical loop, you can use something like this (uses pharo syntax to initialize a dictionary example):

 pd := PluggableDictionary newFromPairs: { 'a' . 2 . 'b' . 1 . 'c' . 3} . (pd associations asSortedCollection: [:x :y | x value < y value]) collect: [:assoc | assoc key]. 

If you need it more often than you might think of introducing your own class that will calculate this collection.

+5
source

If you use VisualWorks, you can use the SortFunction and Symbol β†’ value functions to reduce all this to

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

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

In the second note, perhaps you can change the key and value and just send #asSortedCollection , for example:

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

(Tested in Squeak and Pharo)

+2
source

Got this:

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

Source: https://habr.com/ru/post/1401727/


All Articles