SyntaxStudy
Sign Up
Kotlin Sorting, Searching and Aggregating
Kotlin Beginner 1 min read

Sorting, Searching and Aggregating

Kotlin collections include a comprehensive set of sorting functions. sortedBy and sortedByDescending accept a selector lambda, while sortedWith accepts a Comparator for complex multi-field ordering. The compareBy function creates a Comparator from one or more selector lambdas in priority order. Searching functions include find (returns first match or null), first/last with predicates, indexOfFirst/indexOfLast, contains, and the in operator. The binary search functions work on sorted lists for O(log n) performance. Aggregation functions go beyond simple sum: sumOf, minByOrNull, maxByOrNull, minOfOrNull, maxOfOrNull, average, count with predicates, all, any, and none all operate on any Iterable. These compose naturally into expressive data-processing pipelines.
Example
data class Student(val name: String, val grade: Int, val gpa: Double)

fun main() {
    val students = listOf(
        Student("Alice",  12, 3.9),
        Student("Bob",    11, 3.5),
        Student("Carol",  12, 3.7),
        Student("Dave",   11, 3.8),
        Student("Eve",    10, 4.0),
    )

    // Sort by grade descending, then GPA descending
    val sorted = students.sortedWith(
        compareByDescending<Student> { it.grade }.thenByDescending { it.gpa }
    )
    sorted.forEach { println("${it.name}  grade=${it.grade}  gpa=${it.gpa}") }

    println()

    // Searching
    val topStudent = students.maxByOrNull { it.gpa }
    println("Top student: ${topStudent?.name}")   // Eve

    val firstSenior = students.find { it.grade == 12 }
    println("First senior: ${firstSenior?.name}") // Alice

    // Aggregations
    val avgGpa = students.map { it.gpa }.average()
    println("Average GPA: ${"%.2f".format(avgGpa)}")

    val countHighGpa = students.count { it.gpa >= 3.8 }
    println("Students with GPA >= 3.8: $countHighGpa")   // 3

    val allPassing = students.all { it.gpa >= 2.0 }
    println("All passing: $allPassing")   // true

    val hasPerfect = students.any { it.gpa == 4.0 }
    println("Has 4.0: $hasPerfect")   // true

    // sumOf with selector
    val totalGpa = students.sumOf { it.gpa }
    println("Total GPA: $totalGpa")
}