Inline Comparator for toSortedMap


I am trying to sort the map by values where my sorting criteria is sort on the size of values.
Is there a better way to achieve it than what i have done here?I was thinking of doing it inline but couldn’t achieve it

   class MapValueComparator(givenMap: Map<Int, List<Int>>) : Comparator<Int> {
        val map = givenMap
        override fun compare(o1: Int?, o2: Int?): Int = map[o1]!!.size - map[o2]!!.size
    mapToSort = mapToSort.toSortedMap(MapValueComparator(mapToSort))


You can use compareBy function instead of manually implementing Comparator:

    mapToSort = mapToSort.toSortedMap(compareBy { mapToSort[it]!!.size })

And if you don’t need a sorted map as a result, and just want to have map with entries in the specific order, you can sort entries and place them in a LinkedHashMap:

    mapToSort = mapToSort.entries.sortedBy { it.value.size }.associateBy({ it.key }, { it.value })