How do we iterate and select an element of a set in pharo?

2.3k Views Asked by At

My collection is a Set that contains a number of dictionaries. How can iterate over each dictionary in the Set to select a specific key.

a Set(a Dictionary('age'->'25' 'code'->2512) a Dictionary('age'->'40' 'code'->'1243') a Dictionary('age'->'35' 'code'->'7854'))
2

There are 2 best solutions below

0
On
mySet do: [:each | each do: [ :i | i doStuff ]]

or use detect (I`m not sure if detect works like this, I never used it so far):

mySet do: [:i | i detect: [ :each| (each at: 'key') doStuff ]].

or use keysDo:

mySet do: [:each | each keysDo: [ :k | k doStuff ]]

Check out: http://pharo.gforge.inria.fr/PBE1/PBE1ch10.html

4
On
set := {
    { 'age'->'25'. 'code'->'2512' } asDictionary .
    { 'age'->'40'. 'code'->'1243' } asDictionary.
    { 'age'->'35'. 'code'->'7854' } asDictionary.
} asSet.

If you are interested in retrieving just a single item, then detect: is the way to go. It will return the first item matching the predicate (the block). Note that Set has no defined order, so if you have multiple items matching, it may return different ones at different time.

d := set detect: [ :each | (each at: 'code') = '1243' ].
d. "a Dictionary('age'->'40' 'code'->'1243' )"

If you want to retrieve multiple items that all match the predicate, then use select:

multi := set select: [ :each | (each at: 'age') asNumber >= 35 ].
multi. "a Set(a Dictionary('age'->'40' 'code'->'1243' ) a Dictionary('age'->'35' 'code'->'7854' ))"

Update from comment for commenting:

As Carlos already stated, collect: will do what you need. It applies the transformation block to every item in the collection and then returns a collection of results.

codes := set collect: [ :each | each at: 'code' ].

Works for any collection

#(2 3 4) collect: [ :each | each squared ] "#(4 9 16)"

For further I recommend going through the Collections chapter in Pharo By Example book https://ci.inria.fr/pharo-contribution/job/UpdatedPharoByExample/lastSuccessfulBuild/artifact/book-result/Collections/Collections.html