3

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.

humble_pie
  • 119
  • 10

1 Answers1

1

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]}
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • Yes your right it does work... Is there a way to not sort first element in this case 4.. – humble_pie May 03 '19 at 16:13
  • @humble_pie what's the purpose of the first element? I noticed it's the repeated key of the top-level map. Can such data duplication be removed? – PiotrK May 04 '19 at 13:51