Get values of Map –
We can retrieve values from a mutable map using different methods discussed in the below program.
Kotlin
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) } |
Output:
Team having rank #1 is: India Team having rank #3 is: England Team having rank #4 is: Africa Australia
Kotlin mutableMapOf()
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.
For using the MutableMap interface we need to use functions as shown below
mutableMapOf() or mutableMapOf <K, V>()
For declaring MutableMap Interface
interface MutableMap<K, V> : Map<K, V> (source)
Mutable function example containing Entries, Keys, Values.
Kotlin
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 } |
Output:
Entries: [Box=12, Books=18, Table=13] Keys:[Box, Books, Table] Values:[12, 18, 13]