0
0
KotlinHow-ToBeginner · 3 min read

How to Use Flow Filter in Kotlin for Stream Filtering

In Kotlin, you use the filter operator on a Flow to keep only the elements that match a given condition. This operator takes a lambda that returns true for items you want to keep and false for those you want to skip.
📐

Syntax

The filter operator is called on a Flow and takes a lambda function that returns a Boolean. It emits only the values for which the lambda returns true.

  • flow.filter { value -> condition }: Filters elements based on the condition.
  • The lambda receives each emitted value.
  • Returns a new Flow with filtered values.
kotlin
flow.filter { value -> value % 2 == 0 }
💻

Example

This example creates a flow of numbers from 1 to 5 and filters out only even numbers using filter. It then collects and prints the filtered values.

kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val numbersFlow = (1..5).asFlow()
    val evenNumbersFlow = numbersFlow.filter { it % 2 == 0 }
    evenNumbersFlow.collect { println(it) }
}
Output
2 4
⚠️

Common Pitfalls

One common mistake is forgetting that filter returns a new Flow and does not modify the original flow. Also, using blocking code inside the filter lambda can cause issues because flows are asynchronous.

Another pitfall is not collecting the flow after filtering, so no output appears.

kotlin
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val numbersFlow = (1..5).asFlow()
    // Wrong: filter called but result not collected
    numbersFlow.filter { it % 2 == 0 }

    // Right: collect after filter
    numbersFlow.filter { it % 2 == 0 }.collect { println(it) }
}
Output
2 4
📊

Quick Reference

OperatorDescriptionExample
filterKeeps elements matching a conditionflow.filter { it > 10 }
filterNotKeeps elements NOT matching a conditionflow.filterNot { it % 2 == 0 }
filterIsInstanceKeeps elements of a specific typeflow.filterIsInstance()

Key Takeaways

Use filter on a Flow to emit only elements that satisfy a condition.
Always collect the filtered flow to see the results.
The filter operator returns a new flow; it does not change the original.
Avoid blocking code inside the filter lambda to keep flow asynchronous.
Use related operators like filterNot and filterIsInstance for different filtering needs.