map and filter
- Kotlin course
- Intermediate
- Lesson 64/116
- 5 min
Learn collection transformation with map and filter.
map and filter
map applies a transformation to every element of a list and returns a new list. Example: numbers.map { it * 2 } doubles each number. The original list is unchanged.
filter keeps the elements that satisfy a condition. Example: numbers.filter { it > 5 } takes only numbers greater than five. Both functions take a lambda; it refers to the current element. They can be chained: transform with map first, then narrow with filter.
filter and conditions
filter takes a lambda and collects the elements for which the lambda returns true. The condition must always return a Boolean. Example: numbers.filter { it % 2 == 0 } selects even numbers.
On an empty list filter returns an empty list without error. filterNotNull takes the non-null elements. When map and filter are used together, transformation happens first then selection; order matters because each step produces a new list.
Practice Transform with map and filter
Define val numbers = listOf(1, 2, 3, 4, 5). First double each number with map { it * 2 }, then keep those greater than five with filter { it > 5 } and print the result with println.
Starter code
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
// Double with map, keep greater than five with filter, print with println
}Sample solution
fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.map { it * 2 }.filter { it > 5 }
println(result)
}Expected output
[6, 8, 10]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does numbers.map { it * 2 } return?
- The first element
- Elements matching a condition
- A single total value
- A new list with each element doubled Correct answer
Explanation: map applies a transformation to each element and returns a new list.
2 Complete the map call
numbers.____ { it * 2 }
numbers.map { it * 2 }
Explanation: map doubles each element.
3 Match the map and filter expressions
| Term | Meaning |
|---|---|
map |
Transforms |
filter |
Selects |
{ it * 2 } |
Double |
{ it > 5 } |
Greater than five |