Sequences: Implementation of the drop
Oct 27, 2023
The drop decorator has a similar structure to the take decorator. It also maintains an internal counter and returns elements until the counter reaches zero.
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var left = count
// Shouldn't be called from constructor to avoid premature iteration
private fun drop() {
while (left > 0 && iterator.hasNext()) {
iterator.next()
left--
}
}
override fun next(): T {
drop()
return iterator.next()
}
override fun hasNext(): Boolean {
drop()
return iterator.hasNext()
}
}
You can learn more from my sequences performance study “Measuring sequences”