Introduction
Collection operations make code simpler and easier to read by replacing loops with clear commands.
Collection operations make code simpler and easier to read by replacing loops with clear commands.
collection.operation { item ->
// action or condition
}val numbers = listOf(1, 2, 3, 4) numbers.forEach { println(it) }
val doubled = numbers.map { it * 2 }
val evenNumbers = numbers.filter { it % 2 == 0 }
This program prints a sentence for each fruit using forEach instead of a loop.
fun main() { val fruits = listOf("apple", "banana", "cherry") fruits.forEach { fruit -> println("I like $fruit") } }
Collection operations are safer because they avoid errors like forgetting to update loop counters.
They often run faster because they can be optimized internally.
Using collection operations helps you write code that is easier to maintain and understand.
Collection operations replace loops to make code simpler and clearer.
They work by applying actions or conditions to each item in a collection.
Common operations include map, filter, and forEach.
map and filter often replace traditional loops?map and filter apply actions to each item in a collection in a clear way.items using a collection operation?forEach function is called on the collection like items.forEach { ... }.val numbers = listOf(1, 2, 3, 4)
val result = numbers.filter { it % 2 == 0 }.map { it * 10 }
println(result)val names = listOf("Anna", "Bob", "Cara")
names.map { println(it) }ages = listOf(12, 17, 20, 25, 30), which Kotlin collection operation chain correctly returns a list of ages over 18 multiplied by 2?Pass the test and this pattern moves unknown