I would like to get a list of the values, ordered ...
# getting-started
d
I would like to get a list of the values, ordered by the map key:
Copy code
val a = mapOf(2 to "W", 3 to "V", 1 to "T")
desired result:
Copy code
val list = listOf("T","W","V")
I was reading you can do that using
sortedMap
, but it doesn’t come out on the IDE.
e
Probably something along:
Copy code
val a = mapOf(2 to "W", 3 to "V", 1 to "T")
val arranged = a.values.sorted()
or
Copy code
val a = mapOf(2 to "W", 3 to "V", 1 to "T")
val arranged = a.values.sortedBy { /* your logic here */ }
?
My bad I read the question a bit wrong, maybe you are looking for something like:
Copy code
val a = mapOf(2 to "W", 3 to "V", 1 to "T")
val arranged = a.toSortedMap().values
d
Yes, but
toSortedMap()
doesn’t come up. Maybe because I am using MultiPlaform?
Yes, I just checked, it works on Android, but not on CommonMain.
Any alternative to it?
e
Poor mans substitue:
Copy code
val a = mapOf(2 to "W", 3 to "V", 1 to "T")
val arranged = a.toList().sortedBy { it.first }.map { it.second }
But might make more sense digging into why sortedMap doesn't work
👍 1
w
🤔 Do you have TreeMap? Because the
toSortedMap
extension just does this:
Copy code
public fun <K : Comparable<K>, V> Map<out K, V>.toSortedMap(): SortedMap<K, V> = TreeMap(this)
d
@eHelg is
sortedMap
supported to work on MultiPlatform? uhh, that’s weird. It’s not there.
This is the definition of my map:
Copy code
val myMap = MutableMap<Int, MyObject> = mutableMapOf()
e
No idea, never used MultiPlatform
w
m
Creating a sorted map just for the purpose of sorting seems wasteful to me. Why not use a sequence of pairs, sort them by key and map the value?
v
That's the solution eHelg suggested 🙂
m
Yes, but without creating a map in the process.
v
The map is the given thing
m
In the example, yes.
If the map is a given, I‘d still use sequence over list :-)
👍 1
t
Be aware of this if you consider sequences here: sorting a sequence still creates a list instance in the background and then builds a sequence on that list. If you're fine with a sequence as an end result, then you get a slight benefit from mapping the values out of the sorted entries. But if you need to return any kind of collection, using Sequences just creates unnecessary wrapper instances in this case.
m
Considering that the wrapper instance is really cheap, I’d always try to avoid creating collection explicitly. When you go the sequence route, the implementation can decide whether to use a list or not. Of course for optimum memory performance we could use a mutable list, sort it in-place and then map the values in place, doing everything creating just one collection.
t
Fair point, although something like sorting is never possible on the fly in a sequence. Using the collections directly shows more clearly what the code actually does.