M G
M G

Reputation: 43

How to add new element to map in 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"))))

'''

Upvotes: 3

Views: 5487

Answers (1)

cactustictacs
cactustictacs

Reputation: 19554

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

Upvotes: 2

Related Questions