Count occurrences of each element in a list in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.Collections fun main() { val list: List<String?> = listOf("B", "A", "A", "C", "B", "A") for (item in list.distinct()) { println(item + ": " + Collections.frequency(list, item)) } } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val list = listOf("B", "A", "A", "C", "B", "A") val frequencyMap: MutableMap<String, Int> = HashMap() for (s in list) { var count = frequencyMap[s] if (count == null) count = 0 frequencyMap[s] = count + 1 } println(frequencyMap) } |
Output:
{A=3, B=2, C=1}
That’s all about counting occurrences of each element in a list in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)