Sequence operations in Kotlin

Level 5166 keystrokes

generateSequence creates an infinite, lazy sequence. Elements are produced one by one only as far as needed, so take(5) stops it after five results and toList() collects the squares of the first five even numbers.

Kotlin code

// Infinite sequence 1, 2, 3, ...; each next value is computed from the previous one
1val result = generateSequence(1) { it + 1 }
// Keep only even numbers (lazy: nothing runs yet)
2 .filter { it % 2 == 0 }
// Square each number
3 .map { it * it }
// Limit to the first 5 results, which makes the sequence finite
4 .take(5)
// The terminal operation: only now are the elements computed, up to 10
5 .toList()
6
// Print the heading
7println("First 5 even squares:")
// Prints 4, 16, 36, 64 and 100 on separate lines
8for (n in result) println(n)

Output

First 5 even squares:
4
16
36
64
100
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • (× 6
  • )× 6
  • .× 4
  • {× 3
  • }× 3
  • =× 3
  • "× 2
  • :× 1
  • *× 1
  • %× 1

More Kotlin examples at level 5

← Kotlin typing practice