Terminal operator for Kotlin sequence that discard the output?

Viewed 92

I'm operating on very large Kotlin sequence, I'm executing my logic on every step of the sequence and I never need to keep the whole sequence in memory.

Currently my code looks like this

hugeSequence
    .filter { ... } 
    .map {...... }
    .onEach {
        callExpensiveOperation(it)
    }
    .toList()  <- this feels wrong

The toList() at the bottom is the terminal operator, but I'm worried that Kotlin may try to create a huge list in memory, before realising that I'm not even assign the result value of that operation.

Is there any other terminal operator I can use just to trigger the sequence to start?

1 Answers

Use forEach instead of onEach. It is the terminal equivalent of onEach.

hugeSequence
    .filter { ... } 
    .map {...... }
    .forEach {
        callExpensiveOperation(it)
    }
Related