Grouping and Associating

groupBy and partition

Example

groupBy makes a Map<Key, List>; partition splits into a pair of lists (matching, not matching).

data class Student(val name: String, val branch: String, val cgpa: Double)

fun main() {
    val students = listOf(
        Student("Asha", "CSE", 9.1), Student("Ravi", "ECE", 7.4),
        Student("Kiran", "CSE", 6.8), Student("Meena", "MECH", 8.2),
        Student("John", "ECE", 8.9),
    )
    val byBranch = students.groupBy { it.branch }
    byBranch.forEach { (branch, list) -> println("$branch: ${list.map { it.name }}") }

    println(students.groupBy({ it.branch }, { it.cgpa }))   // key + value selectors
    println(students.groupingBy { it.branch }.eachCount())

    val (eligible, notEligible) = students.partition { it.cgpa >= 7.5 }
    println("Placement eligible: ${eligible.map { it.name }}")
    println("Not eligible:       ${notEligible.map { it.name }}")
}

Output

CSE: [Asha, Kiran]
ECE: [Ravi, John]
MECH: [Meena]
{CSE=[9.1, 6.8], ECE=[7.4, 8.9], MECH=[8.2]}
{CSE=2, ECE=2, MECH=1}
Placement eligible: [Asha, Meena, John]
Not eligible:       [Ravi, Kiran]

associate, associateBy, associateWith

Example

These build a Map from a list. If two elements produce the same key, the last one wins.

data class Product(val sku: String, val name: String, val price: Int)

fun main() {
    val products = listOf(Product("P1", "Mouse", 499), Product("P2", "Keyboard", 999))
    println(products.associateBy { it.sku }.keys)                 // key -> element
    println(products.associate { it.name to it.price })           // key -> value
    println(listOf("apple", "fig").associateWith { it.length })   // element -> value

    val bySku = products.associateBy(Product::sku)
    println(bySku["P2"]?.name)                                     // fast lookup by id
}

Output

[P1, P2]
{Mouse=499, Keyboard=999}
{apple=5, fig=3}
Keyboard