CodeBlanks Logo Icon CodeBlanks

Array methods

Learn array processing with map, filter and forEach.

map, filter, forEach

map transforms each element, filter selects those matching a condition, forEach runs an action for each element. Lambdas use { }; it represents the element.

val nums = intArrayOf(1, 2, 3, 4)
val doubled = nums.map { it * 2 }     // [2, 4, 6, 8]
val even = nums.filter { it % 2 == 0 } // [2, 4]
nums.forEach { println(it) }           // 1, 2, 3, 4

map returns a new list (each element transformed). filter makes a new list of elements where the condition is true. forEach runs an action, returns nothing.

These methods use lambdas (anonymous functions); it is the default parameter name.

Practice Double each element

Write a fun main(). Create an array with val nums = intArrayOf(1, 2, 3, 4). Double each element with val doubled = nums.map { it * 2 }. Print the result with println(doubled).

Starter code

Main.kt
fun main() {
    // Double each element with map
}

Sample solution

Main.kt
fun main() {
    val nums = intArrayOf(1, 2, 3, 4)
    val doubled = nums.map { it * 2 }
    println(doubled)
}

Expected output

[2, 4, 6, 8]

Method chaining

These methods can be chained: nums.filter { ... }.map { ... } first filters then transforms.

val nums = intArrayOf(1, 2, 3, 4, 5, 6)
val result = nums.filter { it % 2 == 0 }.map { it * 10 }
println(result)  // [20, 40, 60]

First even numbers (2, 4, 6) are filtered, then each is multiplied by 10 (20, 40, 60). The chain runs left to right.

Chaining keeps code short and readable; no intermediate variables needed.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does arr.map { it * 2 } do?

  • Reverses the array
  • Selects even numbers
  • Prints each element
  • Multiplies each element by 2 Correct answer

Explanation: map transforms each element; here it multiplies by 2.

2 Complete the map call

Question
val doubled = nums.____ { it * 2 }
Answer
val doubled = nums.map { it * 2 }

Explanation: nums.map { it * 2 } doubles each element.

3 Match the methods

Term Meaning
map { it * 2 } Transforms
filter { it > 0 } Selects
forEach { println(it) } Acts on each
it Lambda parameter

All lessons in Beginner