Create a frequency map in Kotlin
This article explores different ways to create a frequency map in Kotlin.
1. Using groupingBy() function
In Kotlin, you can count the occurrences of elements in a list using the groupingBy() collector. It converts the collection of elements into a map by grouping elements using the specified keySelector function to extract a key from each element.
The following code example shows invocation for this function:
|
1 2 3 4 5 6 |
fun main() { val chars = arrayOf("A", "A", "C", "B", "C", "A") val freqMap: Map<String, Int> = chars.groupingBy { it }.eachCount() println(freqMap) } |
Output:
{A=3, B=1, C=2}
If you need to find all the repeated values in a list, you can filter the values having a count of more than 1.
|
1 2 3 4 5 6 |
fun main() { val chars = arrayOf("A", "A", "C", "B", "C", "A") val freqMap: Map<String, Int> = chars.groupingBy { it }.eachCount().filter { it.value > 1 } println(freqMap) } |
Output:
{A=3, C=2}
2. Using merge() function
Alternatively, you can iterate over the list and use the merge() function to create or append values to the frequency map. The merge() function associates the specified key with the given value if it is not already associated. Otherwise, it replaces the associated value with the results of the given remapping function.
|
1 2 3 4 5 6 7 8 9 |
fun main() { val chars = arrayOf("A", "A", "C", "B", "C", "A") val freqMap: MutableMap<String, Int> = mutableMapOf() for (s in chars) { freqMap.merge(s, 1) { a, b -> a + b } } println(freqMap) } |
Output:
{A=3, B=1, C=2}
3. Naive solution
Finally, you can write your custom logic for transforming a list into the corresponding frequency map. Here’s what the code would look like:
|
1 2 3 4 5 6 7 8 9 10 11 |
fun main() { val chars = arrayOf("A", "A", "C", "B", "C", "A") val freqMap: MutableMap<String, Int> = mutableMapOf() for (s in chars) { val prev = freqMap.getOrDefault(s, 0) freqMap[s] = prev + 1 } println(freqMap) } |
Output:
{A=3, C=2, B=1}
That’s all about creating a frequency map 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 :)