This article explores different ways to count occurrences of each element in a list in Kotlin.

1. Using Collections.frequency() function

The idea is to call the Collections.frequency() function for each distinct element of the list. It returns the total number of occurrences of the specified element in the list.

Download Code

Output:

B: 2
A: 3
C: 1

2. Using MutableMap

Instead of calling the frequency() function for each distinct element, you can construct a MutableMap to store the frequencies of the elements present in a list. This is shown below:

Download Code

Output:

{A=3, B=2, C=1}

That’s all about counting occurrences of each element in a list in Kotlin.