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.
message to your collection, with the element you want to count as the argument:
#( 'apple' 'orange' 'melon' 'banana' 'banana' 'apple' 'melon' 'banana')
If you want to count the occurrences of all the elements, use a Bag:
#( '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.
#( 1 2 3 4 5 6 7 8 ) count: [:x | x < 5]