Skip to content

Collections and sequences

Collections and Sequences Deep Dive

Overview

Kotlin collections are highly expressive, but interview discussions often focus on eagerness, allocation behavior, and immutability semantics.


Core Concepts

Common operations:

  • map
  • filter
  • flatMap
  • groupBy
  • associate

Key nuance:

  • List<T> is read-only from that API surface
  • it is not necessarily deeply immutable

Sequences differ because they are lazy.


Internal Implementation

Collection chains usually allocate intermediate collections. Sequence chains defer work and process lazily.

That means sequences can reduce allocations, but also add iterator/lazy overhead.


JVM / Compiler Behavior

The compiler does not magically optimize every chain away. Standard library operations still correspond to loops, lambdas, and allocated containers depending on API choice.


Code Examples

val names = users
    .filter { it.active }
    .map { it.name }
val names = users.asSequence()
    .filter { it.active }
    .map { it.name }
    .toList()

Common Interview Questions

  • Q: When should you use Sequence? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.
  • Q: Are Kotlin collections immutable? A: Start from delivery semantics: use StateFlow for durable state, SharedFlow or Channel for transient events, and lifecycle-aware collection to prevent duplicate work.
  • Q: Why can operator chains become allocation-heavy? A: Tie Kotlin language features to production outcomes: safety, readability, testability, and runtime or allocation tradeoffs when relevant.

Production Considerations

Use collection chains for readable business logic. Switch to sequences only when dataset size and allocation pressure justify it.


Performance Insights

  • small collections: eager collections are often fine
  • large pipelines: sequences may help
  • hot paths: benchmark rather than assume

Senior-Level Insights

Strong answers avoid blanket rules like β€œSequence is always faster.” Context matters.