Lambdas Workbook (Part 2): The Collection API
Practice problems for Lambdas at Work: Transforming Collections. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.
passing a lambda to a function
1. forEach
Given val names = listOf("Ada", "Linus"), print each name with forEach.
Show answer Hide answer
names.forEach { println(it) } 2. The trailing-lambda convention
Rewrite names.forEach({ n -> println(n) }) in idiomatic form (lambda outside the parentheses, using it).
Show answer Hide answer
names.forEach { println(it) } map and filter
3. map to squares
Turn listOf(1, 2, 3) into [1, 4, 9].
Show answer Hide answer
listOf(1, 2, 3).map { it * it } 4. map to lengths
Given words: List<String>, produce a list of their lengths.
Show answer Hide answer
words.map { it.length } 5. filter
Keep only the even numbers from nums.
Show answer Hide answer
nums.filter { it % 2 == 0 } 6. Chain them
From nums, keep the evens and then square them.
Show answer Hide answer
nums.filter { it % 2 == 0 }.map { it * it } the rest of the toolkit
7. any
Is any element of nums negative?
Show answer Hide answer
nums.any { it < 0 } 8. all
Are all elements of nums positive?
Show answer Hide answer
nums.all { it > 0 } 9. count
How many names in names are longer than three characters?
Show answer Hide answer
names.count { it.length > 3 } 10. find
Get the first element of nums greater than 10, or null if there’s none.
Show answer Hide answer
nums.find { it > 10 } 11. sumOf
Add up the lengths of all words.
Show answer Hide answer
words.sumOf { it.length } your own higher-order function
12. Take a function as a parameter
Write repeatTimes(n: Int, action: (Int) -> Unit) that calls action with 0, 1, … n-1.
Show answer Hide answer
fun repeatTimes(n: Int, action: (Int) -> Unit) {
for (i in 0 until n) action(i)
} 13. Call it with a trailing lambda
Call your repeatTimes to print tick 0, tick 1, tick 2.
Show answer Hide answer
repeatTimes(3) { println("tick $it") } Back to the lesson, Lambdas at Work, or on to part three: closures.
Comments