Consider the following Kotlin code that processes a list of numbers. What will be the output?
val numbers = listOf(1, 2, 3, 4, 5) val eagerResult = numbers .map { println("Mapping $it"); it * 2 } .filter { println("Filtering $it"); it > 5 } val lazyResult = numbers.asSequence() .map { println("Mapping $it"); it * 2 } .filter { println("Filtering $it"); it > 5 } .toList() println("Eager result size: ${eagerResult.size}") println("Lazy result size: ${lazyResult.size}")
Think about when the map and filter functions run in eager vs lazy collections.
In eager processing, map runs on all items first, then filter runs on all mapped items. In lazy processing with sequences, map and filter run together per item, so you see interleaved prints.
Why are Kotlin sequences better for processing large collections compared to regular lists?
Think about how sequences handle each element compared to lists.
Sequences process elements one by one and only when needed, so they don't create extra collections during chained operations. This saves memory and can improve performance on large data.
Look at this Kotlin code snippet. It processes a large list but runs slowly. What is the main cause?
val largeList = (1..1_000_000).toList() val result = largeList .map { it * 2 } .filter { it % 3 == 0 } .take(5) println(result)
Think about how map and filter work on lists versus sequences.
Using map and filter on lists creates new lists at each step, which is expensive for large data. Using sequences would avoid this by processing elements lazily.
Which Kotlin code snippet correctly converts a list to a sequence, filters even numbers, maps them to strings, and collects the result as a list?
Remember the order of operations and that filter must be applied before map for correct filtering.
Option B correctly converts the list to a sequence first, then filters even numbers, maps them to strings, and finally collects to a list. Other options either apply filter after map or miss collecting to a list.
You have a large list of integers. You want to find the first 10 numbers that are multiples of 7 after doubling each number. Which Kotlin code snippet is the most efficient?
Consider lazy evaluation and the order of map and filter for efficiency.
Option D uses sequences to process lazily, doubling first then filtering multiples of 7, and stops after finding 10 results. This avoids processing the entire list. Option D creates intermediate lists and does not collect to a list. Option D filters before doubling, which changes the logic. Option D filters before doubling, which is incorrect for the requirement.