Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new element to map in Kotlin?

Tags:

android

kotlin

How to add an element with the same first key to map and save each element there?

'''

        var records = mutableMapOf<Int, Map<Int, List<String>>>()
        records.put(1, mutableMapOf(Pair(2, listOf<String>("first"))))
        records.put(1, mutableMapOf(Pair(3, listOf<String>("second"))))

'''

like image 475
M G Avatar asked Dec 22 '25 15:12

M G


1 Answers

Maps can only have one value per key, if you add another entry with a key that already exists, it'll overwrite it. You need a value type that's a collection (like List or Set) that you can put multiple things into.

Assuming you want to use Int keys to store items that are Pair<Int, String>, you'll need a MutableMap<Int, MutableList<Pair<Int, String>>> (or a Set, you won't get duplicates and it's unordered usually).

You need to get the collection for a key, and then add to it (or whatever you're doing):

var records = mutableMapOf<Int, MutableList<Pair<Int, String>>>()
// this creates a new empty list if one doesn't exist for this key yet
records.getOrPut(1) { mutableListOf() }.add(Pair(2, "first"))
records.getOrPut(1) { mutableListOf() }.add(3 to "second") // another way to make a Pair
println(records)

>> {1=[(2, first), (3, second)]}

https://pl.kotl.in/AlrSG0KH-

That's a bit wordy so you might want to make some nice addRecord(key, value) etc functions that let you access those inner lists more easily

like image 76
cactustictacs Avatar answered Dec 24 '25 06:12

cactustictacs



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!