0Pricing
Kotlin Academy · Lesson

Association and Flattening

associate and flatMap.

Associating and Flattening

Two more powerful collection tools: associate family functions build maps from a list, and flatMap / flatten turn nested collections into a single flat one.

The associateWith Function

associateWith uses each element as a key and computes its value with a lambda, producing a Map.

fun main() {
    val words = listOf("a", "bb", "ccc")
    val lengths = words.associateWith { it.length }
    println(lengths)
}

All lessons in this course

  1. Filtering and Mapping
  2. Grouping and Partitioning
  3. Aggregation
  4. Association and Flattening
← Back to Kotlin Academy