Back to Blog

Kotlin create a list of even numbers

Sandy LaneSandy Lane

Video: Kotlin create a list of even numbers by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin Create a List of Even Numbers

In Kotlin, generating a list of even numbers can be done efficiently using built-in functions like filter or step in ranges. This example demonstrates how to create a list of even numbers within a specified range using concise and readable Kotlin code.

Code

fun main() {
  // Create a list of even numbers from 1 to 20 using filter
  val numbers = (1..20).toList()
  val evenNumbers = numbers.filter { it % 2 == 0 }
  println("Even numbers using filter: $evenNumbers")

  // Alternatively, create a list of even numbers using step in a range
  val evenNumbersStep = (2..20 step 2).toList()
  println("Even numbers using step: $evenNumbersStep")
}

Key Points

  • Use the filter function with a lambda to select even numbers from any list or range.
  • The step keyword in ranges allows skipping numbers, perfect for generating even numbers directly.
  • Both methods produce a list of even numbers, but step is more concise and efficient when the range is known.
  • Kotlin's range and collection functions make working with sequences of numbers simple and expressive.