Skip to main content

How to find the frequency of elements in an array in Kotlin

How to find the frequency of elements in an array in Kotlin.

Here is a step-by-step tutorial on how to find the frequency of elements in an array in Kotlin.

Step 1: Define an array

First, you need to define an array with a list of elements. You can do this by using the arrayOf function and passing the elements as arguments. Here's an example:

val array = arrayOf(1, 2, 3, 4, 2, 3, 1, 2, 4, 4)

Step 2: Create a frequency map

Next, you need to create a map to store the frequency of each element in the array. In Kotlin, you can use the groupBy function to group the elements by their values, and then use the mapValues function to calculate the frequency of each group. Here's how you can do it:

val frequencyMap = array.groupBy { it }.mapValues { it.value.size }

In this code, groupBy { it } groups the elements by their values, and mapValues { it.value.size } calculates the size of each group, which represents the frequency of each element.

Step 3: Display the frequency

Finally, you can display the frequency of each element in the array. You can iterate over the frequencyMap using a for loop and print the key-value pairs. Here's an example:

for ((element, frequency) in frequencyMap) {
println("$element : $frequency")
}

This code will print each element and its corresponding frequency in the console.

Here's the complete code:

val array = arrayOf(1, 2, 3, 4, 2, 3, 1, 2, 4, 4)
val frequencyMap = array.groupBy { it }.mapValues { it.value.size }

for ((element, frequency) in frequencyMap) {
println("$element : $frequency")
}

When you run this code, you will see the frequency of each element in the array printed in the console.

That's it! You have successfully found the frequency of elements in an array using Kotlin.