links to this page:    
View this PageEdit this PageUploads to this PageHistory of this PageTop of the SwikiRecent ChangesSearch the SwikiHelp Guide
Recipe: Counting elements in a collection
Last updated at 1:10 pm UTC on 16 January 2006
You want to count how often an element occurs in a collection.

Send a


message to your collection, with the element you want to count as the argument:

"print it"
#( 'apple' 'orange' 'melon' 'banana' 'banana' 'apple' 'melon' 'banana')
occurrencesOf: 'apple'

If you want to count the occurrences of all the elements, use a Bag:

"print it"
#( 'apple' 'orange' 'melon' 'banana' 'banana' 'apple' 'melon' 'banana') as: Bag) sortedElements

This gives a SortedCollection with Associations of the form element-count.

See also: The "Testing" protocol of Collection has messages for testing if an element is included in a Collection. There, you can also see how occurrencesOf: is implemented generically in terms of do:.

Counting all the elements that satisfy a certain criterion.

Send a count: message to the collection, giving it a block that contains the criterion.

"print it"
#( 1 2 3 4 5 6 7 8 ) count: [:x | x < 5]