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"))))
'''
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
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