map and filter
- Kotlin course
- Intermediate
- Lesson 91/116
- 5 min
Learn Flow transformation with map and filter.
map and filter: Intermediate operators
map transforms each value; filter passes only values that match a condition. Both are intermediate operators: they return a new Flow and do not run anything. The flow runs only when a terminal operator (collect) is called.
numbers()
.filter { it % 2 == 0 }
.map { it * 10 }
.collect { println(it) }Here, from values 1..5 the even ones (2, 4) are kept, multiplied by 10 (20, 40) and printed. Operators chain; each consumes the previous flow and produces a new one.
The operator chain
Intermediate operators chain; each takes a flow and produces a new one. filter and map run in order: first filter, then transform. When the terminal is called, the whole chain runs top to bottom.
flowOf(1, 2, 3, 4, 5)
.filter { it > 2 }
.map { it * it }
.collect { println(it) }Output: 9, 16, 25 (3², 4², 5²). First 3, 4, 5 are filtered, then each is squared. The chain order directly affects the output.
Practice Build a filter and map chain
Define fun numbers(): Flow<Int> = flowOf(1, 2, 3, 4, 5). Mark main with runBlocking. Inside it call numbers().filter { it % 2 == 0 }.map { it * 10 }.collect { println(it) }. The output prints each result on its own line.
Starter code
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking
// numbers function: return a Flow<Int> of 1, 2, 3, 4, 5
// main: filter even, multiply by 10, print each
fun main() = runBlocking {
// write here
}Sample solution
fun numbers(): Flow<Int> = flowOf(1, 2, 3, 4, 5)
fun main() = runBlocking {
numbers().filter { it % 2 == 0 }.map { it * 10 }.collect { println(it) }
}Expected output
20 40
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the operators
| Term | Meaning |
|---|---|
map { } |
Transforms |
filter { } |
Selects |
intermediate |
Middle step |
collect { } |
Terminal |
2 Transform a value
val doubled = numbers().____ { it * 2 }
val doubled = numbers().map { it * 2 }
Explanation: map transforms each value.
3 What does flow.filter { it % 2 == 0 } do?
- Divides every value by 2
- Passes only even values Correct answer
- Turns every value into an even number
- Sets every value to 0
Explanation: filter passes values that satisfy the condition; drops the rest.