Recipe: Counting elements in a collection
Last updated at 1:10 pm UTC on 16 January 2006
Problem
You want to count how often an element occurs in a collection.
Solution
Send a
occurrencesOf:
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'
Discussion
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:.
Problem
Counting all the elements that satisfy a certain criterion.
Solution
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]