List Filter in Kotlin

Level 3104 keystrokes

Uses filter with a lambda to keep only the even numbers of a list.

Kotlin code

// A list of the numbers 1 to 6
1val nums = listOf(1, 2, 3, 4, 5, 6)
// filter returns a new list of the elements for which the lambda is true
// it is the implicit name of the single parameter; evens is [2, 4, 6]
2val evens = nums.filter { it % 2 == 0 }
3
// Prints 2, 4 and 6, one per line
4for (n in evens) println(n)

Output

2
4
6
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.

  • ,× 5
  • =× 4
  • (× 3
  • )× 3
  • .× 1
  • {× 1
  • }× 1
  • %× 1

More Kotlin examples at level 3

← Kotlin typing practice