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 ?
Hash table based implementation of the MutableMap interface, which additionally preserves the insertion order of entries during the iteration. The insertion order is preserved by maintaining a doubly-linked list of all of its entries.
There is no thread-safety guarantee for the collections returned by mutableMapOf ( MutableMap ), mutableListOf ( MutableList ), or mutableSetOf ( MutableSet ).
Kotlin mutableMapOf() Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.
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.
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"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With