In Kotlin collections:
maptransforms each element into a new value.filterkeeps only elements that match a condition.forEachperforms an action for each element.
map: transform elements
Use map when you want to create a new collection by changing each item.
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { number ->
number * 2
}
println(doubled) // [2, 4, 6, 8]
You can use it when the lambda has one parameter:
val numbers = listOf(1, 2, 3, 4)
val doubled = numbers.map { it * 2 }
println(doubled) // [2, 4, 6, 8]
filter: keep matching elements
Use filter when you want only items that satisfy a condition.
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = numbers.filter { it % 2 == 0 }
println(evenNumbers) // [2, 4, 6]
Another example with strings:
val names = listOf("Alice", "Bob", "Charlie", "Anna")
val namesStartingWithA = names.filter { it.startsWith("A") }
println(namesStartingWithA) // [Alice, Anna]
forEach: perform an action
Use forEach when you want to do something with each element, such as printing.
val names = listOf("Alice", "Bob", "Charlie")
names.forEach { name ->
println(name)
}
Using it:
val names = listOf("Alice", "Bob", "Charlie")
names.forEach {
println(it)
}
Chaining them together
You can combine filter, map, and forEach.
val numbers = listOf(1, 2, 3, 4, 5, 6)
numbers
.filter { it % 2 == 0 }
.map { it * 10 }
.forEach { println(it) }
Output:
20
40
60
This means:
- Keep only even numbers:
[2, 4, 6] - Multiply each by
10:[20, 40, 60] - Print each result
Example with objects
data class User(
val name: String,
val age: Int
)
val users = listOf(
User("Alice", 25),
User("Bob", 17),
User("Charlie", 30)
)
val adultNames = users
.filter { it.age >= 18 }
.map { it.name }
println(adultNames) // [Alice, Charlie]
Important difference
map and filter return new collections:
val numbers = listOf(1, 2, 3)
val doubled = numbers.map { it * 2 }
println(numbers) // [1, 2, 3]
println(doubled) // [2, 4, 6]
forEach is usually used for side effects and does not create a transformed list:
val numbers = listOf(1, 2, 3)
numbers.forEach { println(it) }
Quick summary
val numbers = listOf(1, 2, 3, 4, 5)
val squared = numbers.map { it * it }
// [1, 4, 9, 16, 25]
val greaterThanTwo = numbers.filter { it > 2 }
// [3, 4, 5]
numbers.forEach { println(it) }
// Prints each number
Use:
mapwhen you want to transform valuesfilterwhen you want to select valuesforEachwhen you want to perform an action for each value
