how can I sort a `Map`? alternatively, is there a ...
# getting-started
y
how can I sort a
Map
? alternatively, is there a sorted map type other than
TreeMap
(because that one is a Java thing and gives me platform types)
j
Could you please explain a bit the use case / context for why you need a sorted map?
y
for iteration purposes only
I ended up just implementing a flatmap into a list, which is then sorted.
👌 1
j
Yes, usually maps are data structures meant for lookup, not iteration. So depending on the use case you can derive a list from it
y
yep. forcing a map to be sorted at all times is not what I want or need in this case (or in most cases, probably)
h
why can't you simply do
yourMap.toSortedMap().forEach(...)
?
e
why flatmap? I'd expect
Copy code
.entries.sortedBy { it.key }
to give you what you want
3
k
What exactly could you do if
TreeMap
was a Kotlin type that you can't do because it's a Java type?
y
nothing, this is just me making assumptions that Kotlin implementations are somehow preferred. which doesn't actually seem to be true in many cases. re: flatmap - you're correct. I had to flatmap because the value of my map was more complex, and I forgot to mention this.
e
treemap's platform types in Kotlin aren't great, and its performance relative to hashmap isn't great in Java either, so I can understand wanting an alternative
j
Yeah
TreeMap
is actually most useful when you want to read or remove subtrees based on the sorting of the keys, like "give me the subtree of all keys below 42". If you just want sorted iteration, it's most likely better to just iterate on the sorted entries in the places where you need that.
k
Talking of platform types, I'm confused:
TreeMap
seems to behave as if Kotlin knows its nullability requirements, so the following doesn't compile:
Copy code
java.util.TreeMap<String, String>().put(null as String?, "")
On the other hand, various other Java types that also require an argument to be non-null, do in fact compile:
Copy code
java.io.FileOutputStream(null as java.io.File?)
y
might be relevant: https://kotlinlang.slack.com/archives/C0B8MA7FA/p1674490254501389?thread_ts=1674480790.422839&amp;cid=C0B8MA7FA (please ignore the fact that I re-asked the same question 😞 )
👍 1