Hello, I have a map of format <String, Int> ...
# announcements
t
Hello, I have a map of format <String, Int> and want to sort it ascending by the Int value, how would I do this in Kotlin?
h
Isn't SortedMap sorted by map keys, not by values?
e
Exactly ^
e
ah.. sorry my bad
h
e
toList()/entries -> sortedBy, then
e
Don't forget conversion back to map, because
sortedBy
still returns list of pairs
a
but then you'd have to sort the entries everytime a new entry is added, not sure if this makes much sense
☝️ 1
h
If you convert back to map you're back where you started – a map has no sort order at all.
a
unless it’s a
LinkedHashMap
for example
t
I went with the toList().sortedBy method because I only need the order to be kept strictly when rebuilding the map, thanks for the help 🙂
e
@hho sorry it's kinda late, but still First, I just checked - converted map keeps the order. Second - it is actually logical, because
List.toMap
iterates over sorted list, combining each pair.
a
😉
✔️ 1
a
@arekolek and then you add another item and the ordering is off 😉
a
I agree with you completely, I was addressing the topic of
LinkedHashMap
😛