What if you could transform and pick data with just a few words instead of many lines of code?
Why Sequence operators (map, filter) in Kotlin? - Purpose & Use Cases
Imagine you have a long list of numbers and you want to keep only the even numbers and then double them. Doing this by hand means writing loops, checking conditions, and managing temporary lists.
Writing loops and conditions manually is slow and easy to mess up. You might forget to add a condition or accidentally change the original list. It also makes your code long and hard to read.
Sequence operators like map and filter let you do these steps clearly and quickly. You just say what you want to do, and Kotlin handles the details behind the scenes.
val result = mutableListOf<Int>() for (num in numbers) { if (num % 2 == 0) { val doubled = num * 2 result.add(doubled) } }
val result = numbers.filter { it % 2 == 0 }.map { it * 2 }This makes your code shorter, easier to understand, and less error-prone, so you can focus on what you want to do, not how to do it.
For example, if you have a list of prices and want to apply a discount only to items above a certain price, you can use filter to pick those items and map to apply the discount in a clean way.
Manual loops are slow and error-prone.
map and filter simplify data processing.
They make code shorter, clearer, and easier to maintain.