22

I need to know will the map in kotlin preserve the order of the entries which i have entered during insertion
Example

val data = mutableMapOf<String,String>()
data.put("some_string_1","data_1")
.
.
.
data.put("some_string_n","data_n")

will the order preserve during the iteration of the map ?

hotkey
  • 140,743
  • 39
  • 371
  • 326
Stack
  • 1,164
  • 1
  • 13
  • 26

2 Answers2

35

Yes, it will.

The reference for mutableMapOf() says:

The returned map preserves the entry iteration order.

This is exactly the property that you asked about.

The current implementation (as of Kotlin 1.3.30) returns a LinkedHashMap, which preserves the order by linking the entries. The underlying implementation may change in the future versions, but the entry iteration order will be still guaranteed by the documented function contract.

hotkey
  • 140,743
  • 39
  • 371
  • 326
8

mutableMapOf(Pair...) will create an instance of whatever is considered the default implementation for that platform (probably HashMap).

If you need your data value to preserve insert order you can use linkedMapOf(Pair...)

val data = linkedMapOf(
    "some_string_1" to "data_1",
    "some_string_2" to "data_2",
    "some_string_n" to "data_n"
)
noiaverbale
  • 1,550
  • 13
  • 27