Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize big immutable map in Kotlin?

I have a big dataset. It contains more than 1000 records. This dataset maps one string to another. So it is convenient to use Map<String, String>. The data inside this map are not changed during the application run so the immutable map is ok.

The only way of initialization of Map I found is mapOf function:

testMap = mapOf("One" to "1", "Two" to "2", "Eight" to "8")

But I cannot place the whole of my dataset in one line. It is very inconvenient and the code looks totally unreadable and ugly. The more convenient way of initialization is to read the dataset from a txt file line by line in loop and fill the map by these lines.

Is it possible to fill Map in loop?

like image 444
Andrey Epifantsev Avatar asked Nov 06 '25 23:11

Andrey Epifantsev


1 Answers

You can use a HashMap, and initialize like this:

val map = hashMapOf<String,String>()
for (i in 0..1000){
    // Logic to read txt
    map["key"] = "value"
}
like image 148
Vinicius Almada Avatar answered Nov 09 '25 17:11

Vinicius Almada



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!