Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - Will mutableMapOf() preserve the order which i have entered

Tags:

kotlin

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 ?

like image 276
Stack Avatar asked Apr 15 '19 10:04

Stack


People also ask

Which map maintains the insertion order Kotlin?

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.

Is Kotlin mutableMap thread safe?

There is no thread-safety guarantee for the collections returned by mutableMapOf ( MutableMap ), mutableListOf ( MutableList ), or mutableSetOf ( MutableSet ).

What is mutableMapOf?

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.


2 Answers

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.

like image 73
hotkey Avatar answered Oct 03 '22 04:10

hotkey


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"
)
like image 35
noiaverbale Avatar answered Oct 03 '22 03:10

noiaverbale