Kotlin
Beginner
1 min read
Lists, Sets and Maps
Example
fun main() {
// Read-only list
val fruits = listOf("apple", "banana", "cherry", "date", "elderberry")
// filter + map
val longUpperFruits = fruits
.filter { it.length > 5 }
.map { it.uppercase() }
println(longUpperFruits) // [BANANA, CHERRY, ELDERBERRY]
// flatMap — flatten nested collections
val nested = listOf(listOf(1, 2), listOf(3, 4), listOf(5))
println(nested.flatMap { it }) // [1, 2, 3, 4, 5]
// groupBy
val byLength = fruits.groupBy { it.length }
println(byLength)
// fold and reduce
val sum = listOf(1, 2, 3, 4, 5).fold(0) { acc, n -> acc + n }
val product = listOf(1, 2, 3, 4, 5).reduce { acc, n -> acc * n }
println("sum=$sum product=$product") // 15 120
// Mutable map operations
val scores = mutableMapOf("Alice" to 90, "Bob" to 75)
scores["Carol"] = 88
scores.getOrPut("Dave") { 70 }
println(scores)
// partition — splits into pair of lists
val (evens, odds) = (1..10).partition { it % 2 == 0 }
println("evens=$evens odds=$odds")
// zip
val names = listOf("Alice", "Bob", "Carol")
val points = listOf(100, 200, 150)
val zipped = names.zip(points)
println(zipped) // [(Alice, 100), (Bob, 200), (Carol, 150)]
}