https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
j

Jeff Tycz

04/30/2021, 1:02 AM
In my KMP project I am trying to sort a HashMap by its keys, however I noticed that
toSortedMap
seems not to be available in the common module only the JVM. What is the way to sort a hashmap in the common module?
e

ephemient

04/30/2021, 1:13 AM
depends, do you need a MutableMap, a Map, or just a collection of entries?
j

Jeff Tycz

04/30/2021, 1:14 AM
Right now mutable map but not stuck with it or anything
e

ephemient

04/30/2021, 1:16 AM
there isn't a common MutableMap that maintains sorting order right now, you'd have to build your own 😞
if you just need a read-only Map, the default maps maintain insertion order
j

Jeff Tycz

04/30/2021, 1:18 AM
What would you suggest, I can easily change to something else that could sort as long as I have a way to associate a key with a value. I am trying to build an OAuth header and I need to sort the parameters to create the signature
e

ephemient

04/30/2021, 1:19 AM
map.entries.sortedBy { it.key }.associateBy({ it.key }, { it.value })
would create a new read-only map with ordered keys
1
j

Jeff Tycz

04/30/2021, 1:19 AM
nice that should do just fine!
e

ephemient

04/30/2021, 1:19 AM
if you just need iteration and don't need the Map aspect, you might be able to get away with
map.entries.sortedBy { it.key }
1
(also, sounds like OAuth 1... OAuth 2 is simpler 🙂 )
j

Jeff Tycz

04/30/2021, 1:21 AM
ha yeah it is and I wish I could use OAuth2 but the api I am using does not support it for what I need