0
0
Kotlinprogramming~5 mins

Sequence operators (map, filter) in Kotlin

Choose your learning style9 modes available
Introduction

Sequence operators like map and filter help you change or pick items from a list easily without writing loops.

When you want to change every item in a list to something else.
When you want to keep only certain items from a list based on a rule.
When you want to process data step-by-step without creating many temporary lists.
Syntax
Kotlin
val newSequence = oldSequence.map { item -> transform(item) }
val filteredSequence = oldSequence.filter { item -> condition(item) }

map changes each item and returns a new sequence with the changed items.

filter keeps only items that match the condition you give.

Examples
This doubles each number in the sequence.
Kotlin
val numbers = sequenceOf(1, 2, 3)
val doubled = numbers.map { it * 2 }
This keeps only even numbers from the sequence.
Kotlin
val numbers = sequenceOf(1, 2, 3, 4)
val evenNumbers = numbers.filter { it % 2 == 0 }
This first keeps even numbers, then doubles them.
Kotlin
val numbers = sequenceOf(1, 2, 3, 4)
val doubledEvens = numbers.filter { it % 2 == 0 }.map { it * 2 }
Sample Program

This program takes numbers 1 to 5, keeps only those greater than 2, then multiplies each by 3, and prints them.

Kotlin
fun main() {
    val numbers = sequenceOf(1, 2, 3, 4, 5)
    val filtered = numbers.filter { it > 2 }
    val mapped = filtered.map { it * 3 }
    mapped.forEach { println(it) }
}
OutputSuccess
Important Notes

Sequences process items lazily, which means they do work only when needed.

You can chain map and filter to do multiple steps clearly.

Remember to convert sequences to lists if you want to reuse the results multiple times.

Summary

map changes each item in a sequence.

filter keeps only items that match a condition.

Use these to write clear and simple code for working with lists.