Issue
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?
Solution
Use forEach
instead of onEach
. It is the terminal equivalent of onEach
.
hugeSequence
.filter { ... }
.map {...... }
.forEach {
callExpensiveOperation(it)
}
Answered By - marstran
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.