diff --git a/src/main/kotlin/ru/dbotthepony/mc/otm/core/collect/StreamyIterators.kt b/src/main/kotlin/ru/dbotthepony/mc/otm/core/collect/StreamyIterators.kt index 3a925efff..572e0cb10 100644 --- a/src/main/kotlin/ru/dbotthepony/mc/otm/core/collect/StreamyIterators.kt +++ b/src/main/kotlin/ru/dbotthepony/mc/otm/core/collect/StreamyIterators.kt @@ -25,8 +25,7 @@ import java.util.stream.StreamSupport // Aside parallel work, unimplemented Stream API elements can be easily implemented when required -private class FilteringIterator(private val parent: Iterator, private val predicate: Predicate) : MutableIterator { - private var value: T = parent.next() +private class FilteringIterator(private val parent: Iterator, private val predicate: Predicate, private var value: T) : MutableIterator { private var hasValue = true private var returned = false @@ -78,23 +77,26 @@ private class MappingIterator(private val parent: Iterator, private val private class FlatMappingIterator(private val parent: Iterator, private val mapper: (T) -> Iterator) : MutableIterator { private var current: Iterator = mapper.invoke(parent.next()) private var last: Iterator? = null - private var hasNext = current.hasNext() + + init { + while (!current.hasNext() && parent.hasNext()) { + current = mapper.invoke(parent.next()) + } + } override fun hasNext(): Boolean { - return hasNext + return current.hasNext() } override fun next(): R { - if (!hasNext) + if (!current.hasNext()) throw NoSuchElementException() val v = current.next() last = current - hasNext = false - while (!hasNext && parent.hasNext()) { + while (!current.hasNext() && parent.hasNext()) { current = mapper.invoke(parent.next()) - hasNext = current.hasNext() } return v @@ -183,11 +185,15 @@ fun concatIterators(vararg iterators: Iterator): MutableIterator { * Resulting [Iterator] is [MutableIterator] if [this] is */ fun Iterator.filter(condition: Predicate): MutableIterator { - if (!hasNext()) { - return emptyIterator() + while (hasNext()) { + val v = next() + + if (condition.test(v)) { + return FilteringIterator(this, condition, v) + } } - return FilteringIterator(this, condition) + return emptyIterator() } /**