CodeBlanks Logo Icon CodeBlanks

Summary - Collection stdlib

Combine windowed, chunked and zip to write a data pipeline.

Summary - Collections stdlib

In this group you saw advanced collections stdlib methods: sliding windows with windowed, splitting with chunked, merging/splitting with zip/unzip, running accumulation with scan, and flattening with flatMap/flatten.

This lesson includes a small task that combines three of them: you will split a list with chunked and sum each chunk with sum. This pattern brings together the power of the collections stdlib.

Practice Summary: chunk sums with chunked

In main assign the result of listOf(1, 2, 3, 4, 5, 6).chunked(3) { it.sum() } to a variable and print it with println.

Starter code

Main.kt
// in main split the list 1..6 with chunked(3)
// sum each chunk and print

Sample solution

Main.kt
fun main() {
    val sums = listOf(1, 2, 3, 4, 5, 6).chunked(3) { it.sum() }
    println(sums)
}

Expected output

[6, 15]

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which method shows running intermediate results in a list?

  • reduce
  • fold
  • scan Correct answer
  • forEach

Explanation: scan collects each intermediate result in a list.

2 Match the stdlib methods

Term Meaning
windowed(2) Sliding window
chunked(2) Consecutive chunk
zip(other) Parallel merge
flatMap { } Transform and flatten

3 Complete the chunked call

Question
val sums = listOf(1, 2, 3, 4).____(2) { it.sum() }
Answer
val sums = listOf(1, 2, 3, 4).chunked(2) { it.sum() }

Explanation: chunked(2) yields consecutive pairs.

All lessons in Advanced