Kotlin mutableMapOf()
Kotlin MutableMap é uma interface de estruturas de coleção que contém objetos na forma de chaves e valores. Ele permite que o usuário recupere com eficiência os valores correspondentes a cada chave. A chave e os valores podem ser de pares diferentes, como <Int, String>, <Char, String>, etc.
Para usar a interface MutableMap, precisamos usar as funções mostradas abaixo
mutableMapOf() or mutableMapOf <K, V>()
Para declarar a interface MutableMap
interface MutableMap<K, V> : Map<K, V> (source)
Exemplo de função mutável contendo entradas, chaves, valores.
fun main(args: Array<String>) {
val items = mutableMapOf("Box" to 12, "Books" to 18, "Table" to 13)
println("Entries: " + items.entries) //Printing Entries
println("Keys:" + items.keys) //Printing Keys
println("Values:" + items.values) //Printing Values
}
Saída:
Entries: [Box=12, Books=18, Table=13] Keys:[Box, Books, Table] Values:[12, 18, 13]
Localizando o tamanho do mapa -
Podemos determinar o tamanho do mapa mutável usando dois métodos. Usando a propriedade size do mapa e usando o método count().
fun main(args : Array<String>) {
val ranks = mutableMapOf(1 to "India",2 to "Australia",
3 to "England",4 to "Africa")
//method 1
println("The size of the mutablemap is: "+ranks.size)
//method 2
println("The size of the mutablemap is: "+ranks.count())
}
Saída:
The size of the mutablemap is: 4 The size of the mutablemap is: 4
Obtenha os valores do Mapa -
Podemos recuperar valores de um mapa mutável usando diferentes métodos discutidos no programa abaixo.
fun main() {
val ranks = mutableMapOf(1 to "India",2 to "Australia",
3 to "England",4 to "Africa")
//method 1
println("Team having rank #1 is: "+ranks[1])
//method 2
println("Team having rank #3 is: "+ranks.getValue(3))
//method 3
println("Team having rank #4 is: "+ranks.getOrDefault(4, 0))
// method 4
val team = ranks.getOrElse(2 ,{ 0 })
println(team)
}
Saída:
Team having rank #1 is: India Team having rank #3 is: England Team having rank #4 is: Africa Australia
funções put() e putAll()
As funções put() e putAll() são usadas para adicionar elementos na função MutableMap.put() adiciona um único elemento por vez, enquanto a função putAll() pode ser usada para adicionar vários elementos por vez em MutableMap.
Programa Kotlin que usa as funções put() e putAll() -
fun main(args: Array<String>) {
val mutableMap = mutableMapOf<String, String>()
mutableMap.put("Name", "Geek")
mutableMap.put("Country", "India")
val map = mapOf<String,String>("Department" to "Computer Science",
"Hobby" to "Coding")
println("<----Traverse mutableMap---->")
for (key in mutableMap.keys) {
println("Key = "+key +", "+"Value = "+mutableMap[key])
}
mutableMap.putAll(map)
println("<----Traversal after putting hashmap---->")
for (key in mutableMap.keys) {
println("Key = "+key +", "+"Value = "+mutableMap[key])
}
}
Saída:
<----Traverse mutableMap----> Key = Name, Value = Geek Key = Country, Value = India <----Traversal after putting hashmap----> Key = Name, Value = Geek Key = Country, Value = India Key = Department, Value = Computer Science Key = Hobby, Value = Coding
remover (chave) e remover (chave, valor) função -
A função remove (key) é usada para remover o valor que corresponde à sua chave mencionada.
A função remove (chave, valor) é usada para remover elementos que contêm chaves e valores.
Programa Kotlin para demonstrar a função remove() -
fun main(args: Array<String>) {
val mutableMap = mutableMapOf<String, String>()
mutableMap.put("Name", "Geek")
mutableMap.put("Company", "GeeksforGeeks")
mutableMap.put("Country", "India")
for (key in mutableMap.keys) {
println("Key = ${key}, Value = ${mutableMap[key]}")
}
println()
println("Remove the Key: "+mutableMap.remove("Country"))
println()
println("Is pair removes from the map: "
+mutableMap.remove("Company","GeeksforGeeks"))
println()
println("<---Traverse Again--->")
for (key in mutableMap.keys) {
println("Key = ${key}, Value = ${mutableMap[key]}")
}
}
Saída:
Key = Name, Value = Geek Key = Company, Value = GeeksforGeeks Key = Country, Value = India Remove the Key: India Is pair removes from the map: true <---Traverse Again---> Key = Name, Value = Geek
função clear() -
Usado para remover todos os elementos do mutableMap.
Programa Kotlin de usar a função clear() -
fun main(args: Array<String>) {
val mutableMap: MutableMap<String, String> = mutableMapOf<String, String>()
mutableMap.put("Name", "Geek")
mutableMap.put("Company", "GeeksforGeeks")
for (key in mutableMap.keys) {
println("Key = ${key}, Value = ${mutableMap[key]}")
}
println("mutableMap.clear()")
println("Method called to clear the map: "+mutableMap.clear())
println("Map Empty: "+mutableMap)
}
Saída:
Key = Name, Value = Geek Key = Company, Value = GeeksforGeeks mutableMap.clear() Method called to clear the map: kotlin.Unit Map Empty: {}
Traversal em um mapa mutável -
Traversing significa viajar por cada nó nas estruturas de dados como Linked List, Arrays, Trees, etc.
Significa apenas viajar para cada nó pelo menos uma vez para exibi-lo ao usuário ou realizar uma operação nele.
Para entender isso, vamos dar um exemplo abaixo do
programa Kotlin para demonstrar a travessia -
fun main(args: Array<String>) { //Declaring function
//Creating MutableMap of different types
val mutableMap = mutableMapOf(1 to "Aditya",
4 to "Vilas", 2 to "Manish", 3 to "Manjot")
for (key in mutableMap.keys) {
println("Key = ${key}, Value = ${mutableMap[key]}")
}
}
Saída:
Key = 1, Value = Aditya Key = 4, Value = Vilas Key = 2, Value = Manish Key = 3, Value = Manjot
As postagens do blog Acervo Lima te ajudaram? Nos ajude a manter o blog no ar!
Faça uma doação para manter o blog funcionando.
70% das doações são no valor de R$ 5,00...
Diógenes Lima da Silva