Real World Example

Scanning Server Logs

A support engineer at a payments company needs the first 3 failed UPI transactions above Rs 5,000 from a log with millions of lines. With a sequence the program reads lines lazily and stops as soon as it has 3 matches. The log here is generated, but File.useLines gives exactly the same Sequence<String>.

Example

data class Txn(val id: String, val status: String, val amount: Int, val method: String)

fun logLines(): Sequence<String> = generateSequence(1) { it + 1 }
    .take(2_000_000)
    .map { i ->
        val status = if (i % 97 == 0) "FAILED" else "SUCCESS"
        val method = if (i % 3 == 0) "CARD" else "UPI"
        "TXN$i,$status,${(i * 37) % 20_000},$method"
    }

fun parse(line: String): Txn {
    val (id, status, amount, method) = line.split(",")
    return Txn(id, status, amount.toInt(), method)
}

fun main() {
    var linesRead = 0
    val suspicious = logLines()
        .onEach { linesRead++ }
        .map(::parse)
        .filter { it.status == "FAILED" && it.method == "UPI" && it.amount > 5000 }
        .take(3)
        .toList()
    suspicious.forEach { println("${it.id}  Rs ${it.amount}") }
    println("Lines read: $linesRead of 2000000")
}

Output

TXN194  Rs 7178
TXN388  Rs 14356
TXN485  Rs 17945
Lines read: 485 of 2000000