Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Association

In a Map, one type of data is associated with another. Using association, we can create Maps from List of data also. There are three ways in which we can create a Map from List :

associate()

Given each list item, we compute both key & value for its corresponding map entry.

listItem → **key**, **value**

 list.associate { item -> /* return Pair */ }
 

Example (Simple)

Given a List<String> where each list item is of the format key | value, create a Map<String, Int>

 fun main() {
    val list = listOf(
        "A | 1", "B | 2", "C | 3"
    )
    
    val map = list.associate {
        val (key, value) = it.split(" | ")
        key to value.toInt()
    }
    
    println(map)
}

// Output : {A=1, B=2, C=3}
 

Example 2 (OOPs)

Given a List<Person(id, name)>, create a Map<String, String> where key is person’s id and value is person’s name.

 
data class Person(
    val id: String,
    val name: String
)

fun main() {
    val persons = listOf(
        Person("A1", "Alpha"),
        Person("B1", "Beta")
    )
    
    val idToNameMap = persons.associate {
        it.id to it.name
    }
    
    println(idToNameMap)
}

// Output : {A1=Alpha, B1=Beta}
 

associateBy()

Given each list item, we compute the key for its corresponding map entry where list item itself is the value.

listItem → **key**, listItem

 list.associateWith { item -> /* Return key */ }
 

Example (Simple)

Given a List<String> - names, create a Map<Char, String> where key is the name’s first letter & value is the name itself.

 fun main() {
    val names = listOf(
        "Apple", "Boat", "Coat"
    )

    val initialToNameMap = names.associateBy {
        it[0]
    }

    println(initialToNameMap)
}

// Output : {A=Apple, B=Boat, C=Coat}
 

Example (OOPs)

Given a List<Person(id, name)>, create a Map<String, String> where key is person’s name & value is the person object.

 
data class Person(
    val id: String,
    val name: String
)

fun main() {
    val persons = listOf(
        Person("A1", "Alpha"),
        Person("B1", "Beta")
    )

    val idToPersonMap = persons.associateBy { it.id }

    println(idToPersonMap)
}

// Output : {A1=Person(id=A1, name=Alpha), B1=Person(id=B1, name=Beta)}
 

associateWith()

Given each list item, we compute the value for its corresponding map entry where list item itself is the key.

listItem → listItem, **value**

 list.associateWith { item -> /* Return value */ }
 

Example (Simple)

Given a List<String> - names, create a Map<String, Int> where key is the name itself & value is the number of vowels in it.

 fun main() {
    val names = listOf(
        "Apple", "Google", "Microsoft"
    )

    val nameToNoOfVowelsMap = names.associateWith {
        it.noOfVowels()
    }

    println(nameToNoOfVowelsMap)
}

// Counts the number of vowels in a String
fun String.noOfVowels(): Int {
    val vowels = listOf('a', 'e', 'i', 'o', 'u')
    return lowercase()
        .toCharArray()
        .count { it in vowels }
}

// Output : {Apple=2, Google=3, Microsoft=3}
 

Example (OOPs)

Given a List<Person(id, name, orders: List<Order(id, amount)>)>, create a Map<String, Int> where key is person object itself & value is the total of all the order’s amount.

 
data class Order(
    val id: String,
    val amount: Int
)

data class Person(
    val id: String,
    val name: String,
    val orders: List<Order>
)

fun main() {
    val persons = listOf(
        Person(
            id = "A1",
            name = "Alpha",
            orders = listOf(
                Order("O1", 100),
                Order("O2", 500),
            )
        ),
        Person(
            id = "B1",
            name = "Beta",
            orders = listOf(
                Order("O3", 50),
                Order("O4", 1000),
            )
        )
    )

    val personToOrdersTotalMap = persons.associateWith { person ->
        person.orders.sumOf { it.amount }
    }

    println(personToOrdersTotalMap)
}

// Output : {Person(id=A1, name=Alpha, orders=[Order(id=O1, amount=100), Order(id=O2, amount=500)])=600, Person(id=B1, name=Beta, orders=[Order(id=O3, amount=50), Order(id=O4, amount=1000)])=1050}