Search code examples
kotlinmutablemap

Having an issue with mutablemap in Kotlin


I'm working on an algorithm type challenge, and i am debugging via print statements and i can't seem to figure out why the the values for keys are not what i am expecting

 var mapNums = mutableMapOf<Int, Int>()

//imaginary array
    //var nums = [34,28,11,21,3,34,8,7,34,7,31,7,3,28,18]
    var count = 0
    

    for (n in nums) {

        if (mapNums.containsKey(n)) {
            count ++
            mapNums[n] = count
        } else if (!mapNums.containsKey(n)) {
            count = 1
            mapNums[n] = count
        }

    }

    println(mapNums)

//prints {34=2, 28=4, 11=1, 21=1, 3=3, 8=1, 7=2, 31=1, 18=1}

as you can see the key and values aren't what theyre supposed to be and i am not sure why.


Solution

  • You can use the following code to generate the desired map:

    val nums = intArrayOf(34, 28, 11, 21, 3, 34, 8, 7, 34, 7, 31, 7, 3, 28, 18).toList()
    println(nums.groupingBy { it }.eachCount())
    

    try it yourself

    Here groupingBy creates a Grouping source using the same element as the key selector. Then eachCount groups elements from the Grouping source by key and counts elements in each group.

    You can also refer the documentation for more info about groupingBy and eachCount.