
name.remal.java.util.stream.Stream.kt Maven / Gradle / Ivy
package name.remal
import java.util.*
import java.util.stream.Collectors
import java.util.stream.Stream
import java.util.stream.StreamSupport
import kotlin.collections.LinkedHashSet
fun emptyStream(): Stream = Stream.of()
fun streamOf(): Stream = Stream.of()
fun streamOf(vararg elements: T): Stream = Stream.of(*elements)
fun Array.stream(): Stream = Arrays.stream(this)
operator fun Stream.plus(other: Stream): Stream = Stream.concat(this, other)
fun Stream.filterNotNull(): Stream = filter { null != it }.uncheckedCast()
fun Stream.filterIsInstance(type: Class): Stream = filter { type.isInstance(it) }.uncheckedCast()
inline fun Stream.filterIsInstance(): Stream = filterIsInstance(R::class.java)
@JvmName("flatMapCollection")
fun Stream.flatMap(mapper: (T) -> Collection): Stream = this.flatMap { mapper(it).stream() }
@JvmName("flatMapIterable")
fun Stream.flatMap(mapper: (T) -> Iterable): Stream = this.flatMap { StreamSupport.stream(mapper(it).spliterator(), false) }
fun Stream.firstOrNull(): T? = findFirst().orNull
fun Stream.asIterable(): Iterable = object : Iterable {
override fun iterator() = [email protected]()
}
fun Stream.toList(): List = collect(Collectors.toList())
fun Stream.toSet(): Set = collect(Collectors.toCollection(::LinkedHashSet))
fun Stream.toHashSet(): Set = collect(Collectors.toCollection(::HashSet))
fun > Stream.toSortedSet(): SortedSet = collect(Collectors.toCollection { TreeSet() })
fun > Stream.toMap(): Map = collect(Collectors.toMap({ it.first }, { it.second }, { _, value -> value }, ::LinkedHashMap))
fun > Stream.toHashMap(): Map = collect(Collectors.toMap({ it.first }, { it.second }, { _, value -> value }, ::HashMap))
fun , V, T : Pair> Stream.toHashMap(): SortedMap = collect(Collectors.toMap({ it.first }, { it.second }, { _, value -> value }, ::TreeMap))
@JvmName("joinCharSequencesToString")
fun Stream.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = ""): String = collect(Collectors.joining(separator, prefix, postfix))
fun Stream.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = ""): String = map { "$it" }.joinToString(separator, prefix, postfix)
fun > Stream.max(): T? = max(Comparator.naturalOrder()).orNull
fun > Stream.min(): T? = min(Comparator.naturalOrder()).orNull
fun Stream.reduce(reducer: (first: T, second: T) -> T): T? = collect(Collectors.reducing(reducer)).orNull
© 2015 - 2025 Weber Informatics LLC | Privacy Policy