How to work with Maps in Kotlin
Asked Answered
E

5

81

The code below is creating a new map called nameTable, then adding an entry named example to it, then trying to print the name property of the Value.

When I run it, it seems that the plus operation didn't add a new entry to the map like I thought it would.

So what am I doing wrong?

class Person(name1: String, lastName1: String, age1: Int){
    var name: String = name1
    var lastName: String = lastName1
    var age: Int = age1
}

var nameTable: MutableMap<String, Person> = mutableMapOf()
var example = Person("Josh", "Cohen", 24)

fun main (args: Array<String>){
    nameTable.plus(Pair("person1", example))
    for(entry in nameTable){
        println(entry.value.age)
    }
}

While we're at it, I would love some examples of how to add, remove, and get an entry from a map.

Exarch answered 26/5, 2016 at 15:7 Comment(0)
I
76

The reason for your confusion is that plus is not a mutating operator, meaning that it works on (read-only) Map, but does not change the instance itself. This is the signature:

operator fun <K, V> Map<out K, V>.plus(pair: Pair<K, V>): Map<K, V>

What you want is a mutating operator set, defined on MutableMap:

operator fun <K, V> MutableMap<K, V>.set(key: K, value: V)

So your code may be rewritten (with some additional enhancements):

class Person(var name: String, var lastName: String, var age: Int)

val nameTable = mutableMapOf<String, Person>()
val example = Person("Josh", "Cohen", 24)

fun main (args: Array<String>) {
    nameTable["person1"] = example

    for((key, value) in nameTable){
        println(value.age)
    }
}
Ill answered 26/5, 2016 at 18:20 Comment(0)
V
21

The plus-method on Map creates a new map that contains the new entry. It does not mutate the original map. If you want to use this method, you would need to do this:

fun main() {
    val table = nameTable.plus(Pair("person1", example))
    for (entry in table) {
        println(entry.value.age)
    }
}

If you want to add the entry to the original map, you need to use the put method like in Java.

This would work:

fun main() {
    nameTable.put("person1", example)
    for (entry in nameTable) {
        println(entry.value.age)
   }
} 

To get and remove entries from the MutableMap, you can use this:

nameTable["person1"] // Syntactic sugar for nameTable.get("person1")
nameTable.remove("person1")
Venery answered 26/5, 2016 at 15:34 Comment(2)
By the way, anyone knows why there isn't a operator fun minus(key: K) method on Kotlin maps?Venery
in v1.1 the minus operator was added kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/…Mg
W
10

It's too much trouble,You can assign values directly,like this:

@Test
@Throws(Exception::class)
fun main(){

    val map:MutableMap<String,Person> = mutableMapOf()

    map["Josh"]= Person("Josh", "Cohen", 24)

    map.forEach { t, u ->
        println("map key:$t,map value:${u.toString()}")
    }
}

class Person(name1:String, lastName1:String, age1:Int){
    var name:String = name1
    var lastName:String = lastName1
    var age:Int = age1

    override fun toString(): String {
        return "name:$name,lastNam:$lastName,age:$age \n"
    }
}
Watersick answered 23/8, 2017 at 1:35 Comment(0)
M
4

You have to use

put

method.

class Person(name1:String, lastName1:String, age1:Int){
    var name:String = name1
    var lastName:String = lastName1
    var age:Int = age1
}
var nameTable:MutableMap<String, Person> = mutableMapOf()
var example = Person("Josh", "Cohen", 24)
fun main (args: Array<String>){
    nameTable.put("person1", example)
    for(entry in nameTable){
        println(entry.value.age)
    }
}
Musgrove answered 23/8, 2017 at 1:11 Comment(0)
S
1
val params: MutableMap<String, String> = HashMap<String, String>()
    params.put("1", "A")
    params.put("2", "B")
Santoro answered 26/7, 2022 at 10:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.