Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Grouping

We can group a list of data based on a parameter. Parameter may be a field (if we have list of objects) or it can be a computed parameter. Grouping operation creates a Map where key is the paramater we choose & value is the list of all the list items matching that particular parameter. We use the groupBy() function to perform grouping on a list.

 list.groupBy { item -> /* return parameter */ }
 

Example (Simple)

Given a string, count the number of alphabets, digits & other characters in it.

 fun main() {
    val text = "namaste world 1 !"
    val occurrences = text
        .groupBy {
            when {
                it.isLetter() -> "Alphabets"
                it.isDigit() -> "Digits"
                else -> "Other"
            }
        }.mapValues {
            it.value.count()
        }

    println(occurrences)
}

// Output : {Alphabets=12, Other=4, Digits=1}
 

Working :

Example (OOPs)

Given a List<Person(name, gender)> - persons, group them based on their gender.

 enum class Gender { Male, Female, Other }

data class Person(
    val name: String,
    val gender: Gender
) {
    override fun toString() = name
}

fun main() {
    val persons = listOf(
        Person("Alpha", Gender.Male),
        Person("Beta", Gender.Female),
        Person("Alpha1", Gender.Male),
        Person("Beta1", Gender.Female),
        Person("Gamma", Gender.Other)
    )

    val genderToPersonsMap = persons.groupBy { it.gender }

    println(genderToPersonsMap)
}

// Output : {Male=[Alpha, Alpha1], Female=[Beta, Beta1], Other=[Gamma]}