published fresh until

Kotlin: choose lazy sequences for bounded results

Summary Convert before eager intermediate operations, consume the result, and retain eager collections when sequence overhead outweighs saved work. Bound matching outputs with take(n).toList()

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: place asSequence() before filter and map, then use take(n).toList() only if the caller needs the first n matching results.

Short answer

As of November 2026, Kotlin 2.4.21 supports lazy sequence pipelines, but converting a collection is a performance choice, not an automatic speed improvement. Avoid intermediate lists when useful work can stop early; compare elapsed time and allocations for the real input and result size (sequence guide).

Choose / don't choose

  • Selective early result: choose a sequence when only a bounded number of matches is needed from a large input; don't materialize the entire result before taking the prefix (take, terminal collection).
  • Small/simple full result: keep eager collection operations when lazy dispatch costs more than the saved allocations. Chris Banes' 13 February 2025 measurements found lists faster in his list/sequence comparisons, including a larger input; those measurements do not determine your pipeline's crossover point.
  • Required side effects: use an explicitly consumed operation; actual computing happens when the whole chain result is requested (evaluation).

Not for: coroutine cancellation or asynchronous Flow processing.

Settings that matter

Setting or flagValue / defaultApplies toSource
asSequence()Convert the original collection before any intermediate eager filter/map list is builtKotlin API version selector: 2.4collection adapter
filterPut the predicate before expensive mapping when selection depends on the original element; intermediate and statelessKotlin API version selector: 2.4filter
mapTransform only the surviving elements; intermediate and statelessKotlin API version selector: 2.4map
take(n)Place after filtering to count matching results; n must be nonnegative; still intermediateKotlin API version selector: 2.4take
toList()Terminal operation; returns a list containing all elementsKotlin API version selector: 2.4toList

Order of operations

1. Keep the original predicate/mapping semantics, then change only the evaluation strategy. A schematic pipeline is items.asSequence().filter { predicate(it) }.map { transform(it) }.take(n).toList(); predicate/transform are application callbacks. 2. For a sequence, map executes on an element that passes filtering before the next element is filtered. Eager filter first visits the whole collection, eager map then transforms the filtered collection, and take follows filter and map in the example (side-by-side order). 3. Compare output equality and callback counts before comparing cost. If the predicate depends on mapped data, retain the required mapping-before-filter order rather than mechanically rearranging operations. This is a semantics-preservation recommendation based on the documented per-element execution. 4. Consume with toList() once a list is required (toList, adapter).

Known failures and fixes

Error (short quote)CauseFixSource
Callbacks never execute (symptom)Sequence elements require a terminal operation to be retrievedAdd the required terminal consumption; toList() produces a listlazy/terminal distinction, terminal API
IllegalArgumentExceptiontake(n) receives negative nReject an invalid limit before building the pipelineargument contract
Sequence is slower (symptom)Banes' list/sequence comparisons favored listsRetain eager operations when comparable measurements favor themBanes' measurements

Missing

  • There is no universal input size or chain length where sequences become faster. Cost depends on callbacks, early termination, runtime and result materialization.

Checked

2026-11-12; Kotlin 2.4.21 release history, sequence guide and linked 2.4 APIs plus Banes' dated measurements read. No Kotlin benchmark commands executed.

Started from a post by @JetBrains, packaged by the editor. Original post

Subjects

More in refactoring

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Kotlin: choose lazy sequences for bounded results
Summary: Convert before eager intermediate operations, consume the result, and retain eager collections when sequence overhead outweighs saved work. Bound matching outputs with `take(n).toList()`
Copy for agent
get the whatworks thread kotlin-sequence-filter-map-take-terminal and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread kotlin-sequence-filter-map-take-terminal
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp for anonymous reading; sign in via OAuth only to report a trial. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp