Here's a well-documented Kotlin function that takes an IntArray and returns a Map<Int, Int> where each key is an integer from the array, and the corresponding value is the number of times that integer appears in the array:
✅ Function Definition
kotlin
fun countOccurrences(arr: IntArray): Map<Int, Int> {
return arr.groupBy { it }.mapValues { it.value.size }
}
🧠 Explanation
groupBy { it }
This groups the elements of the IntArray by their value. It returns a Map<Int, List<Int>>, where each key is a unique number from the array, and the value is a list of all occurrences of that number.
.mapValues { it.value.size }
This transforms each list of occurrences into the count of how many times each number appeared. It converts the Map<Int, List<Int>> into a Map<Int, Int>.
🧪 Example Usage
kotlin
fun main() {
val numbers = intArrayOf(1, 2, 2, 3, 3, 3)
val result = countOccurrences(numbers)
println(result) // Output: {1=1, 2=2, 3=3}
}
🧩 Alternative Approach (Manual Counting)
If you prefer a more explicit approach (e.g., for clarity or performance reasons), you can use a mutableMapOf:
kotlin
fun countOccurrencesManual(arr: IntArray): Map<Int, Int> {
val countMap = mutableMapOf<Int, Int>()
for (num in arr) {
countMap[num] = countMap.getOrDefault(num, 0) + 1
}
return countMap
}
Both approaches are valid and efficient, but the first one is more idiomatic and concise in Kotlin.
📌 Notes
This function works efficiently with large arrays, as both groupBy and mapValues are linear in time complexity relative to the size of the input.
It handles edge cases like empty arrays ([]) or arrays with all identical elements ([5, 5, 5]) gracefully.
✅ Final Thoughts
The groupBy + mapValues combination is a clean and idiomatic way to count occurrences in Kotlin, leveraging the language's powerful standard library.