Search code examples
kotlinmutablemap

Kotlin sorting Mutable map of strings


Why cannot I sort a mutable map of string. My map is declared as follows.

val schedule:  MutableMap<String, ArrayList<String>>

It gives me schedule object as follows.

{1=[1], 0=[0], 3=[3], 2=[2], 5=[5], 4=[4, 14.07, 16.07, 01.08, 10.08], 6=[6]}

Now for day 4, I would to sort the elements in ascending order, ideally ignoring first element. I want my output to look like below.

{1=[1], 0=[0], 3=[3], 2=[2], 5=[5], 4=[4, 1.08, 10.08, 14.07, 16.07], 6=[6]}

I can access the required day with schedule.schedule["4"]?.sorted() but this doesn't do anything. I tired converting Strings to Ints but still no luck.


Solution

  • Use sort() instead of sorted().

    • sort() sorts "in place": it mutates the ArrayList
    • sorted() returns a new sorted ArrayList

    Try it: https://repl.it/repls/BitterRapidQuark

    val map = mutableMapOf("4" to arrayListOf<String>("4", "14.07", "16.07", "01.08", "10.08"))
    println("Original: " + map) // {4=[4, 14.07, 16.07, 01.08, 10.08]}
    
    map["4"]?.sorted()
    println("Not mutated: " + map) // {4=[4, 14.07, 16.07, 01.08, 10.08]}
    
    map["4"]?.sort()
    println("Mutated: " + map) // {4=[01.08, 10.08, 14.07, 16.07, 4]}