Lesson 5 of 8
Collections & Lambdas
Learn , maps and , and how like filter, map, sumOf and groupBy replace many hand-written . This style is common in Android code.
fun main() {
// Read-only vs mutable is explicit:
val nums = listOf(3, 1, 4, 1, 5, 9) // List<Int>
val mut = mutableListOf(1, 2) // can add/remove
mut.add(3)
val ages = mapOf("Ada" to 17, "Alan" to 16)
println(ages["Ada"]) // 17
val unique = setOf(1, 2, 2, 3) // {1, 2, 3}
// Lambdas: { parameters -> body }
val double = { n: Int -> n * 2 }
println(double(21)) // 42
}data class Student(val name: String, val grade: Int)
fun main() {
val students = listOf(
Student("Ada", 95),
Student("Alan", 88),
Student("Grace", 92),
Student("Linus", 76),
)
// 'it' = the single lambda parameter:
val honorRoll = students
.filter { it.grade >= 90 }
.map { it.name }
.sorted()
println(honorRoll) // [Ada, Grace]
val avg = students.map { it.grade }.average()
val best = students.maxByOrNull { it.grade }
val byPass = students.groupBy { it.grade >= 80 }
val total = students.sumOf { it.grade }
students.forEach { println(it.name) }
// first/any/all/none:
students.any { it.grade == 100 } // false
students.all { it.grade >= 70 } // true
}Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.