Transforming Collections

map, mapIndexed, mapNotNull

Collection operations never change the original collection; they return a new one. map converts every element.

Example

fun main() {
    val prices = listOf(100, 250, 400)
    println(prices.map { it * 1.18 })                      // add GST
    println(prices.mapIndexed { i, p -> "${i + 1}. Rs $p" })

    val inputs = listOf("12", "abc", "7", "")
    println(inputs.mapNotNull { it.toIntOrNull() })        // drops nulls

    val stock = mapOf("pen" to 10, "book" to 0)
    println(stock.mapValues { (_, qty) -> if (qty > 0) "In stock" else "Sold out" })
}

Output

[118.0, 295.0, 472.0]
[1. Rs 100, 2. Rs 250, 3. Rs 400]
[12, 7]
{pen=In stock, book=Sold out}

flatMap and flatten

Example

flatMap maps each element to a list and joins all the lists into one.

data class Order(val id: Int, val items: List<String>)

fun main() {
    val orders = listOf(
        Order(1, listOf("Milk", "Bread")),
        Order(2, listOf("Eggs")),
        Order(3, listOf("Milk", "Butter")),
    )
    println(orders.flatMap { it.items })
    println(orders.flatMap { it.items }.distinct())
    println(listOf(listOf(1, 2), listOf(3), emptyList()).flatten())
}

Output

[Milk, Bread, Eggs, Milk, Butter]
[Milk, Bread, Eggs, Butter]
[1, 2, 3]