// Created on savesnippets.com · https://savesnippets.com/9odM8UdoTDGDWP fun main() { // Eager — every step builds a new List val list = (1..1_000_000) .toList() .map { it * 2 } // allocates List of 1M elements .filter { it % 3 == 0 } // allocates again .take(10) // only 10 wanted — but already did all the work above println(list.size) // 10 // Lazy — each element flows through the full pipeline before the next starts val seq = (1..1_000_000).asSequence() .map { it * 2 } .filter { it % 3 == 0 } .take(10) // stops as soon as 10 are produced .toList() println(seq.size) // 10 — but did vastly less work // Infinite sequences with generateSequence val fibs = generateSequence(0 to 1) { (a, b) -> b to (a + b) } .map { it.first } .take(15) .toList() println(fibs) // [0, 1, 1, 2, 3, 5, 8, 13, 21, ...] // Rule of thumb: use Sequence when the chain is LONG or the input is HUGE. // For small lists, plain List + .map { ... } is simpler and JIT-friendly. }