smalltalkvisualworks

How to sort according to key in an Ordered Collection in Smalltalk


I am trying to sort an OrderedCollection via its keys, but this method returns just the keys. I want to get both keys and values, but sorted based on keys.

aAssociation:= Association new.
aAssociation key:6 value:7.
aOrderedCollection:= OrderedCollection new.
aOrderedCollection addFirst: aAssociation.
aAssociation1:= Association new.
aAssociation1 key:5 value:9.
aOrderedCollection addLast: aAssociation1.
aAssociation2:= Association new.
aAssociation2 key:8 value:4.
aOrderedCollection addLast: aAssociation2.
aSortedCollection:= (aOrderedCollection sort: #key ascending) collect:#key. 

Solution

  • You’re calling #collect: at the end, which is where you extract the keys. Don’t do that and you’re done.

    Also don’t call #sort:, it would modify the collection you send it to. Use #sorted:, it will return a sorted copy. It will also work on all kinds of collections.