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:

Download Code

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.

Download Code

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.

Download Code

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:

Download Code

Output:

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

That’s all about creating a frequency map in Kotlin.