Skip to content

Instantly share code, notes, and snippets.

@danneu
Last active December 8, 2016 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danneu/e89619e63d036a84c00f311471de81dc to your computer and use it in GitHub Desktop.
Save danneu/e89619e63d036a84c00f311471de81dc to your computer and use it in GitHub Desktop.
// Example
//
// val nodes: List<Iterable<Int>> = listOf(
// listOf(1),
// listOf(2),
// listOf(3)
// )
//
// LazyIteratorChain.fromIterables(nodes).asSequence().toList() == listOf(1, 2, 3)
import java.util.Collections
abstract class LazyIteratorChain<T>: Iterator<T> {
var currIter: Iterator<T> = Collections.emptyIterator()
var count = 0
abstract fun nextIterator(count: Int): Iterator<T>?
override fun hasNext(): Boolean {
while (true) {
if (currIter.hasNext()) return true
currIter = nextIterator(++count) ?: return false
}
}
override fun next(): T = currIter.next()
companion object {
fun <T> fromIterables(ables: List<Iterable<T>>) = object : LazyIteratorChain<T>() {
override fun nextIterator(count: Int) = ables.getOrNull(count - 1)?.iterator()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment