Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Transform

Basic collections

We can transform all elements of a list and create a new list using the map() function :

 // Syntax :
coll.map { /* Return new value */ }
 

Example :

 fun main() {
    // Create list of squares of numbers from a list
    val nums = 1..5
    val squares = nums.map { it * it }
    println(squares)
}

// Output : [1, 4, 9, 16, 25]
 

Map

Transform all keys of a Map

You can transform all keys of a map and create a new map using mapKeys function :

 map.mapKeys { (key, value) -> /* return new key */ }
 

Example :

 fun main() {
    var map = mapOf(
        "apple" to 2f,
        "saudi aramco" to 1.8f,
        "microsoft" to 1.7f
    )
    
    // Transform all keys to uppercase
    map = map.mapKeys { it.key.uppercase() }
    
    println(map)
}

// Output : {APPLE=2.0, SAUDI ARAMCO=1.8, MICROSOFT=1.7}
 

Transform all values of a Map

You can transform all values of a map and create a new map using mapValues function :

 map.mapValues { (key, value) -> /* return new value */ }
 

Example :

 fun main() {
    var map = mapOf(
        "apple" to 2f,
        "saudi aramco" to 1.8f,
        "microsoft" to 1.7f
    )
    
    // Transform all values to "$ <amt> Trillion" format
    val newMap = map.mapValues { "$ ${it.value} Trillion" }
    
    println(newMap)
}

// Output : {apple=$ 2.0 Trillion, saudi aramco=$ 1.8 Trillion, microsoft=$ 1.7 Trillion}
 

Transform all entries of a Map

You can transform all entries of a map and create a new map using map function :

 map.map { (key, value) -> /* return new pair */ }
 

Example :

 fun main() {
    var map = mapOf(
        "apple" to 2f,
        "saudi aramco" to 1.8f,
        "microsoft" to 1.7f
    )
    
    // Transform
    val newMap = map.map {
        it.key.uppercase() to "$ ${it.value} Trillion"
    }.toMap()
    
    println(newMap)
}

// Output : {APPLE=$ 2.0 Trillion, SAUDI ARAMCO=$ 1.8 Trillion, MICROSOFT=$ 1.7 Trillion}
 

Note that map() function returns List<Pair<K, V>>. To convert it to a map, we have used toMap() function.