=== Top of the Swiki === Attachments ===

Recipe: Counting Elements in a Collection

Problem

You want to count how often an element occurs in a collection.

Solution

Send a occurrencesOf: message to your collection, giving it the element you want to count as an 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:.

Questions

How do you count all the elements that satisfy a certain criterion?