Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 560
humble_pie Avatar asked Jun 07 '26 02:06

humble_pie


1 Answers

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]}
like image 60
Jean Logeart Avatar answered Jun 10 '26 12:06

Jean Logeart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!