com.itangcent.common.utils.Iterables.kt Maven / Gradle / Ivy
package com.itangcent.common.utils
import java.util.stream.Stream
import java.util.stream.StreamSupport
object Iterables {
fun asIterable(generator: () -> T?): Iterable {
return IterableFromGenerator(generator)
}
}
fun Iterable.asGenerator(): () -> T? {
val iterator = this.iterator()
return {
if (iterator.hasNext()) {
iterator.next()
} else {
null
}
}
}
fun Iterable.asStream(): Stream {
return StreamSupport.stream(this.spliterator(), false)
}
fun Iterator.map(transform: (T) -> R): Iterator {
return IteratorTransformed(this, transform)
}
internal class IterableTransformed(
private val iterable: Iterable,
private val transform: (T) -> R
) : Iterable {
override fun iterator(): Iterator {
return IteratorTransformed(iterable.iterator(), transform)
}
}
internal class IteratorTransformed(
private val iterator: Iterator,
private val transform: (T) -> R
) : Iterator {
override fun hasNext(): Boolean {
return iterator.hasNext()
}
override fun next(): R {
return transform(iterator.next())
}
}
internal class IterableFromGenerator(private val generator: () -> T?) : Iterable {
override fun iterator(): Iterator {
return IteratorFromGenerator(generator)
}
}
internal class IteratorFromGenerator(private val generator: () -> T?) : Iterator {
private var next: T? = null
override fun hasNext(): Boolean {
if (next != null) {
return true
}
next = generator()
return next != null
}
override fun next(): T {
val ret = next
next = null
return ret!!
}
}