Order preservation of Kotlin map keys

Viewed 706

I have not been able to find any explicitly stated documentation that addresses order preservation for the following case.

val map = mapOf(
"k2" to "v1",
"k1" to "v2",
"k3" to "v3" 
)

val keys = map.keys.toList()

I would expect keys to always be in the following order:

["k2", "k1", "k3"]

Is it guaranteed that the order of keys be preserved in the same order they were initialized?

1 Answers

Yes, if you look at implementation of mapOf, it used LinkedHashMap which from Java docs says that it normally preservers key order, unless in case of re-inserting key.

But in case internal implementation might change for some reason I would rather suggest using linkedMapOf in same way as you did mapOf.

LinkedHashMap uses LinkedKeySet implementation when returning Set of keys which ensures correct order.

Related