Rename Stream<T> to Sequence<T> and provide migration path via deprecated types and functions.

This commit is contained in:
Ilya Ryzhenkov
2015-03-10 18:10:57 +03:00
parent 9684d217b3
commit e448f40756
47 changed files with 1906 additions and 556 deletions
@@ -40,12 +40,10 @@ public class ConvertToConcatenatedStringIntention : JetSelfTargetingIntention<Je
val entries = element.getEntries()
val result = entries.stream()
.withIndices()
.map { indexToEntry ->
val (index, entry) = indexToEntry
entry.toSeparateString(quote, convertExplicitly = index == 0, isFinalEntry = index == entries.size - 1)
.mapIndexed { index, entry ->
entry.toSeparateString(quote, convertExplicitly = index == 0, isFinalEntry = index == entries.size() - 1)
}
.makeString(separator = "+")
.join(separator = "+")
.replaceAll("""$quote\+$quote""", "")
val replacement = JetPsiFactory(element).createExpression(result)
@@ -10,5 +10,6 @@
// REF: (for IntArray in kotlin).joinToString(String,String,String,Int,String)
// REF: (for Iterable<T> in kotlin).joinToString(String,String,String,Int,String)
// REF: (for LongArray in kotlin).joinToString(String,String,String,Int,String)
// REF: (for Sequence<T> in kotlin).joinToString(String,String,String,Int,String)
// REF: (for ShortArray in kotlin).joinToString(String,String,String,Int,String)
// REF: (for Stream<T> in kotlin).joinToString(String,String,String,Int,String)
@@ -34,7 +34,7 @@ public class StdLibTestToJSTest extends StdLibQUnitTestSupport {
// TODO review: somethings FAILED if run:
"js/JsDomTest.kt",
"dom/DomTest.kt",
"collections/StreamTest.kt",
"collections/SequenceTest.kt",
"collections/IterableTests.kt",
"language/RangeTest.kt",
"language/RangeIterationTest.kt"
@@ -97,6 +97,16 @@ public inline fun <K, V> Map<K, V>.all(predicate: (Map.Entry<K, V>) -> Boolean):
return true
}
/**
* Returns *true* if all elements match the given *predicate*
*/
public inline fun <T> Sequence<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns *true* if all elements match the given *predicate*
*/
@@ -201,6 +211,16 @@ public fun <K, V> Map<K, V>.any(): Boolean {
return false
}
/**
* Returns *true* if collection has at least one element
*/
public fun <T> Sequence<T>.any(): Boolean {
for (element in this) return true
return false
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns *true* if collection has at least one element
*/
@@ -305,6 +325,16 @@ public inline fun <K, V> Map<K, V>.any(predicate: (Map.Entry<K, V>) -> Boolean):
return false
}
/**
* Returns *true* if any element matches the given [predicate]
*/
public inline fun <T> Sequence<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns *true* if any element matches the given [predicate]
*/
@@ -407,6 +437,17 @@ public fun <K, V> Map<K, V>.count(): Int {
return size()
}
/**
* Returns the number of elements
*/
public fun <T> Sequence<T>.count(): Int {
var count = 0
for (element in this) count++
return count
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the number of elements
*/
@@ -522,6 +563,17 @@ public inline fun <K, V> Map<K, V>.count(predicate: (Map.Entry<K, V>) -> Boolean
return count
}
/**
* Returns the number of elements matching the given [predicate]
*/
public inline fun <T> Sequence<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the number of elements matching the given [predicate]
*/
@@ -630,6 +682,17 @@ public inline fun <T, R> Iterable<T>.fold(initial: R, operation: (R, T) -> R): R
return accumulator
}
/**
* Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element
*/
public inline fun <T, R> Sequence<T>.fold(initial: R, operation: (R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Accumulates value starting with *initial* value and applying *operation* from left to right to current accumulator value and each element
*/
@@ -857,6 +920,15 @@ public inline fun <K, V> Map<K, V>.forEach(operation: (Map.Entry<K, V>) -> Unit)
for (element in this) operation(element)
}
/**
* Performs the given *operation* on each element
*/
public inline fun <T> Sequence<T>.forEach(operation: (T) -> Unit): Unit {
for (element in this) operation(element)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Performs the given *operation* on each element
*/
@@ -951,6 +1023,16 @@ public inline fun <T> Iterable<T>.forEachIndexed(operation: (Int, T) -> Unit): U
for (item in this) operation(index++, item)
}
/**
* Performs the given *operation* on each element, providing sequential index with the element
*/
public inline fun <T> Sequence<T>.forEachIndexed(operation: (Int, T) -> Unit): Unit {
var index = 0
for (item in this) operation(index++, item)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Performs the given *operation* on each element, providing sequential index with the element
*/
@@ -1085,6 +1167,22 @@ public fun <T : Comparable<T>> Iterable<T>.max(): T? {
return max
}
/**
* Returns the largest element or null if there are no elements
*/
public fun <T : Comparable<T>> Sequence<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the largest element or null if there are no elements
*/
@@ -1294,6 +1392,27 @@ public inline fun <R : Comparable<R>, T : Any> Iterable<T>.maxBy(f: (T) -> R): T
return maxElem
}
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
public inline fun <R : Comparable<R>, T : Any> Sequence<T>.maxBy(f: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = f(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
@@ -1469,6 +1588,22 @@ public fun <T : Comparable<T>> Iterable<T>.min(): T? {
return min
}
/**
* Returns the smallest element or null if there are no elements
*/
public fun <T : Comparable<T>> Sequence<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the smallest element or null if there are no elements
*/
@@ -1678,6 +1813,27 @@ public inline fun <R : Comparable<R>, T : Any> Iterable<T>.minBy(f: (T) -> R): T
return minElem
}
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
public inline fun <R : Comparable<R>, T : Any> Sequence<T>.minBy(f: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = f(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = f(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
@@ -1823,6 +1979,16 @@ public fun <K, V> Map<K, V>.none(): Boolean {
return true
}
/**
* Returns *true* if collection has no elements
*/
public fun <T> Sequence<T>.none(): Boolean {
for (element in this) return false
return true
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns *true* if collection has no elements
*/
@@ -1927,6 +2093,16 @@ public inline fun <K, V> Map<K, V>.none(predicate: (Map.Entry<K, V>) -> Boolean)
return true
}
/**
* Returns *true* if no elements match the given *predicate*
*/
public inline fun <T> Sequence<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns *true* if no elements match the given *predicate*
*/
@@ -2073,6 +2249,21 @@ public inline fun <T> Iterable<T>.reduce(operation: (T, T) -> T): T {
return accumulator
}
/**
* Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element
*/
public inline fun <T> Sequence<T>.reduce(operation: (T, T) -> T): T {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty iterable can't be reduced")
var accumulator = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Accumulates value starting with the first element and applying *operation* from left to right to current accumulator value and each element
*/
@@ -2352,6 +2543,19 @@ public inline fun <T> Iterable<T>.sumBy(transform: (T) -> Int): Int {
return sum
}
/**
* Returns the sum of all values produced by [transform] function from elements in the collection
*/
public inline fun <T> Sequence<T>.sumBy(transform: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += transform(element)
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all values produced by [transform] function from elements in the collection
*/
@@ -2484,6 +2688,19 @@ public inline fun <T> Iterable<T>.sumByDouble(transform: (T) -> Double): Double
return sum
}
/**
* Returns the sum of all values produced by [transform] function from elements in the collection
*/
public inline fun <T> Sequence<T>.sumByDouble(transform: (T) -> Double): Double {
var sum: Double = 0.0
for (element in this) {
sum += transform(element)
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all values produced by [transform] function from elements in the collection
*/
+302
View File
@@ -431,6 +431,17 @@ public fun <T> Iterable<T>.contains(element: T): Boolean {
return indexOf(element) >= 0
}
/**
* Returns true if *element* is found in the collection
*/
public fun <T> Sequence<T>.contains(element: T): Boolean {
if (this is Collection<*>)
return contains(element)
return indexOf(element) >= 0
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns true if *element* is found in the collection
*/
@@ -526,6 +537,22 @@ public fun <T> List<T>.elementAt(index: Int): T {
return get(index)
}
/**
* Returns element at given *index*
*/
public fun <T> Sequence<T>.elementAt(index: Int): T {
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
throw IndexOutOfBoundsException("Collection doesn't contain element at index")
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns element at given *index*
*/
@@ -668,6 +695,29 @@ public fun <T> List<T>.first(): T {
return this[0]
}
/**
* Returns first element.
* @throws NoSuchElementException if the collection is empty.
*/
public fun <T> Sequence<T>.first(): T {
when (this) {
is List<*> -> {
if (isEmpty())
throw NoSuchElementException("Collection is empty")
else
return this[0] as T
}
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty")
return iterator.next()
}
}
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns first element.
* @throws NoSuchElementException if the collection is empty.
@@ -793,6 +843,17 @@ public inline fun <T> Iterable<T>.first(predicate: (T) -> Boolean): T {
* Returns the first element matching the given [predicate].
* @throws NoSuchElementException if no such element is found.
*/
public inline fun <T> Sequence<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("No element matching predicate was found")
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* "Returns the first element matching the given [predicate].
* @throws NoSuchElementException if no such element is found.
*/
public inline fun <T> Stream<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("No element matching predicate was found")
@@ -897,6 +958,28 @@ public fun <T> List<T>.firstOrNull(): T? {
return if (isEmpty()) null else this[0]
}
/**
* Returns the first element, or null if the collection is empty.
*/
public fun <T> Sequence<T>.firstOrNull(): T? {
when (this) {
is List<*> -> {
if (isEmpty())
return null
else
return this[0] as T
}
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
return iterator.next()
}
}
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the first element, or null if the collection is empty.
*/
@@ -1007,6 +1090,16 @@ public inline fun <T> Iterable<T>.firstOrNull(predicate: (T) -> Boolean): T? {
/**
* Returns the first element matching the given [predicate], or `null` if element was not found
*/
public inline fun <T> Sequence<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns first element matching the given [predicate], or `null` if element was not found
*/
public inline fun <T> Stream<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
@@ -1149,6 +1242,21 @@ public fun <T> Iterable<T>.indexOf(element: T): Int {
return -1
}
/**
* Returns first index of [element], or -1 if the collection does not contain element
*/
public fun <T> Sequence<T>.indexOf(element: T): Int {
var index = 0
for (item in this) {
if (element == item)
return index
index++
}
return -1
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns first index of [element], or -1 if the collection does not contain element
*/
@@ -1295,6 +1403,21 @@ public inline fun <T> List<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
return -1
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element
*/
public inline fun <T> Sequence<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns index of the first element matching the given [predicate], or -1 if the collection does not contain such element
*/
@@ -1454,6 +1577,22 @@ public inline fun <T> List<T>.indexOfLast(predicate: (T) -> Boolean): Int {
return -1
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element
*/
public inline fun <T> Sequence<T>.indexOfLast(predicate: (T) -> Boolean): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (predicate(item))
lastIndex = index
index++
}
return lastIndex
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns index of the last element matching the given [predicate], or -1 if the collection does not contain such element
*/
@@ -1604,6 +1743,22 @@ public fun <T> List<T>.last(): T {
return this[lastIndex]
}
/**
* Returns the last element.
* @throws NoSuchElementException if the collection is empty.
*/
public fun <T> Sequence<T>.last(): T {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty")
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the last element.
* @throws NoSuchElementException if the collection is empty.
@@ -1798,6 +1953,25 @@ public inline fun <T> Iterable<T>.last(predicate: (T) -> Boolean): T {
return last as T
}
/**
* Returns the last element matching the given [predicate].
* @throws NoSuchElementException if no such element is found.
*/
public inline fun <T> Sequence<T>.last(predicate: (T) -> Boolean): T {
var last: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
last = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection doesn't contain any element matching predicate")
return last as T
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the last element matching the given [predicate].
* @throws NoSuchElementException if no such element is found.
@@ -1962,6 +2136,22 @@ public fun <T> Iterable<T>.lastIndexOf(element: T): Int {
return lastIndex
}
/**
* Returns last index of *element*, or -1 if the collection does not contain element
*/
public fun <T> Sequence<T>.lastIndexOf(element: T): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (element == item)
lastIndex = index
index++
}
return lastIndex
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns last index of *element*, or -1 if the collection does not contain element
*/
@@ -2064,6 +2254,21 @@ public fun <T> List<T>.lastOrNull(): T? {
return if (isEmpty()) null else this[size() - 1]
}
/**
* Returns the last element, or `null` if the collection is empty
*/
public fun <T> Sequence<T>.lastOrNull(): T? {
val iterator = iterator()
if (!iterator.hasNext())
return null
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the last element, or `null` if the collection is empty
*/
@@ -2214,6 +2419,21 @@ public inline fun <T> Iterable<T>.lastOrNull(predicate: (T) -> Boolean): T? {
return last
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> Sequence<T>.lastOrNull(predicate: (T) -> Boolean): T? {
var last: T? = null
for (element in this) {
if (predicate(element)) {
last = element
}
}
return last
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@@ -2372,6 +2592,30 @@ public fun <T> List<T>.single(): T {
}
}
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/
public fun <T> Sequence<T>.single(): T {
when (this) {
is List<*> -> return when (size()) {
0 -> throw NoSuchElementException("Collection is empty")
1 -> this[0] as T
else -> throw IllegalArgumentException("Collection has more than one element")
}
else -> {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Collection is empty")
var single = iterator.next()
if (iterator.hasNext())
throw IllegalArgumentException("Collection has more than one element")
return single
}
}
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the single element, or throws an exception if the collection is empty or has more than one element.
*/
@@ -2575,6 +2819,25 @@ public inline fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T {
return single as T
}
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element
*/
public inline fun <T> Sequence<T>.single(predicate: (T) -> Boolean): T {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) throw IllegalArgumentException("Collection contains more than one matching element")
single = element
found = true
}
}
if (!found) throw NoSuchElementException("Collection doesn't contain any element matching predicate")
return single as T
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element
*/
@@ -2697,6 +2960,26 @@ public fun <T> List<T>.singleOrNull(): T? {
return if (size() == 1) this[0] else null
}
/**
* Returns single element, or `null` if the collection is empty or has more than one element.
*/
public fun <T> Sequence<T>.singleOrNull(): T? {
when (this) {
is List<*> -> return if (size() == 1) this[0] as T else null
else -> {
val iterator = iterator()
if (!iterator.hasNext())
return null
var single = iterator.next()
if (iterator.hasNext())
return null
return single
}
}
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns single element, or `null` if the collection is empty or has more than one element.
*/
@@ -2892,6 +3175,25 @@ public inline fun <T> Iterable<T>.singleOrNull(predicate: (T) -> Boolean): T? {
return single
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found
*/
public inline fun <T> Sequence<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found
*/
@@ -161,6 +161,15 @@ public fun <T> Iterable<T>.drop(n: Int): List<T> {
return list
}
/**
* Returns a sequence containing all elements except first [n] elements
*/
public fun <T> Sequence<T>.drop(n: Int): Sequence<T> {
return DropSequence(this, n)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements except first [n] elements
*/
@@ -335,6 +344,15 @@ public inline fun <T> Iterable<T>.dropWhile(predicate: (T) -> Boolean): List<T>
return list
}
/**
* Returns a sequence containing all elements except first elements that satisfy the given [predicate]
*/
public fun <T> Sequence<T>.dropWhile(predicate: (T) -> Boolean): Sequence<T> {
return DropWhileSequence(this, predicate)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements except first elements that satisfy the given [predicate]
*/
@@ -423,6 +441,15 @@ public inline fun <T> Iterable<T>.filter(predicate: (T) -> Boolean): List<T> {
return filterTo(ArrayList<T>(), predicate)
}
/**
* Returns a sequence containing all elements matching the given [predicate]
*/
public fun <T> Sequence<T>.filter(predicate: (T) -> Boolean): Sequence<T> {
return FilteringSequence(this, true, predicate)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements matching the given [predicate]
*/
@@ -507,6 +534,15 @@ public inline fun <T> Iterable<T>.filterNot(predicate: (T) -> Boolean): List<T>
return filterNotTo(ArrayList<T>(), predicate)
}
/**
* Returns a sequence containing all elements not matching the given [predicate]
*/
public fun <T> Sequence<T>.filterNot(predicate: (T) -> Boolean): Sequence<T> {
return FilteringSequence(this, false, predicate)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements not matching the given [predicate]
*/
@@ -535,6 +571,15 @@ public fun <T : Any> Iterable<T?>.filterNotNull(): List<T> {
return filterNotNullTo(ArrayList<T>())
}
/**
* Returns a sequence containing all elements that are not null
*/
public fun <T : Any> Sequence<T?>.filterNotNull(): Sequence<T> {
return FilteringSequence(this, false, { it == null }) as Sequence<T>
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements that are not null
*/
@@ -558,6 +603,16 @@ public fun <C : MutableCollection<in T>, T : Any> Iterable<T?>.filterNotNullTo(d
return destination
}
/**
* Appends all elements that are not null to the given [destination]
*/
public fun <C : MutableCollection<in T>, T : Any> Sequence<T?>.filterNotNullTo(destination: C): C {
for (element in this) if (element != null) destination.add(element)
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements that are not null to the given [destination]
*/
@@ -646,6 +701,16 @@ public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterNotTo(desti
return destination
}
/**
* Appends all elements not matching the given [predicate] to the given [destination]
*/
public inline fun <T, C : MutableCollection<in T>> Sequence<T>.filterNotTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements not matching the given [predicate] to the given [destination]
*/
@@ -742,6 +807,16 @@ public inline fun <T, C : MutableCollection<in T>> Iterable<T>.filterTo(destinat
return destination
}
/**
* Appends all elements matching the given [predicate] into the given [destination]
*/
public inline fun <T, C : MutableCollection<in T>> Sequence<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements matching the given [predicate] into the given [destination]
*/
@@ -1046,6 +1121,15 @@ public fun <T> Iterable<T>.take(n: Int): List<T> {
return list
}
/**
* Returns a sequence containing first *n* elements
*/
public fun <T> Sequence<T>.take(n: Int): Sequence<T> {
return TakeSequence(this, n)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing first *n* elements
*/
@@ -1190,6 +1274,15 @@ public inline fun <T> Iterable<T>.takeWhile(predicate: (T) -> Boolean): List<T>
return list
}
/**
* Returns a sequence containing first elements satisfying the given [predicate]
*/
public fun <T> Sequence<T>.takeWhile(predicate: (T) -> Boolean): Sequence<T> {
return TakeWhileSequence(this, predicate)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing first elements satisfying the given [predicate]
*/
+71 -4
View File
@@ -270,7 +270,16 @@ public inline fun <T, R, V> Iterable<T>.merge(other: Iterable<R>, transform: (T,
}
/**
* Returns a stream of values built from elements of both collections with same indexes using provided *transform*. Stream has length of shortest stream.
* Returns a sequence of values built from elements of both collections with same indexes using provided *transform*. Resulting sequence has length of shortest input sequences.
*/
public fun <T, R, V> Sequence<T>.merge(sequence: Sequence<R>, transform: (T, R) -> V): Sequence<V> {
return MergingSequence(this, sequence, transform)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream of values built from elements of both collections with same indexes using provided *transform*. Resulting stream has length of shortest input streams.
*/
public fun <T, R, V> Stream<T>.merge(stream: Stream<R>, transform: (T, R) -> V): Stream<V> {
return MergingStream(this, stream, transform)
@@ -456,6 +465,26 @@ public inline fun <T> Iterable<T>.partition(predicate: (T) -> Boolean): Pair<Lis
return Pair(first, second)
}
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
* while *second* collection contains elements for which predicate yielded *false*
*/
public inline fun <T> Sequence<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Splits original collection into pair of collections,
* where *first* collection contains elements for which predicate yielded *true*,
@@ -673,7 +702,16 @@ public fun <T> Iterable<T>.plus(collection: Iterable<T>): List<T> {
}
/**
* Returns a stream containing all elements of original stream and then all elements of the given *collection*
* Returns a sequence containing all elements of original sequence and then all elements of the given [collection]
*/
public fun <T> Sequence<T>.plus(collection: Iterable<T>): Sequence<T> {
return MultiSequence(sequenceOf(this, collection.sequence()))
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements of original stream and then all elements of the given [collection]
*/
public fun <T> Stream<T>.plus(collection: Iterable<T>): Stream<T> {
return Multistream(streamOf(this, collection.stream()))
@@ -769,6 +807,15 @@ public fun <T> Iterable<T>.plus(element: T): List<T> {
return answer
}
/**
* Returns a sequence containing all elements of original sequence and then the given element
*/
public fun <T> Sequence<T>.plus(element: T): Sequence<T> {
return MultiSequence(sequenceOf(this, sequenceOf(element)))
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements of original stream and then the given element
*/
@@ -777,7 +824,16 @@ public fun <T> Stream<T>.plus(element: T): Stream<T> {
}
/**
* Returns a stream containing all elements of original stream and then all elements of the given *stream*
* Returns a sequence containing all elements of original sequence and then all elements of the given [sequence]
*/
public fun <T> Sequence<T>.plus(sequence: Sequence<T>): Sequence<T> {
return MultiSequence(sequenceOf(this, sequence))
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements of original stream and then all elements of the given [stream]
*/
public fun <T> Stream<T>.plus(stream: Stream<T>): Stream<T> {
return Multistream(streamOf(this, stream))
@@ -937,7 +993,18 @@ public fun String.zip(other: String): List<Pair<Char, Char>> {
}
/**
* Returns a stream of pairs built from elements of both collections with same indexes. Stream has length of shortest stream.
* Returns a sequence of pairs built from elements of both collections with same indexes.
* Resulting sequence has length of shortest input sequences.
*/
public fun <T, R> Sequence<T>.zip(sequence: Sequence<R>): Sequence<Pair<T, R>> {
return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 }
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream of pairs built from elements of both collections with same indexes.
* Resulting stream has length of shortest input streams.
*/
public fun <T, R> Stream<T>.zip(stream: Stream<R>): Stream<Pair<T, R>> {
return MergingStream(this, stream) { (t1, t2) -> t1 to t2 }
+14
View File
@@ -45,6 +45,20 @@ public fun <T : Any> List<T?>.requireNoNulls(): List<T> {
return this as List<T>
}
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
public fun <T : Any> Sequence<T?>.requireNoNulls(): Sequence<T> {
return FilteringSequence(this) {
if (it == null) {
throw IllegalArgumentException("null element found in $this")
}
true
} as Sequence<T>
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
+133 -1
View File
@@ -94,7 +94,16 @@ public inline fun <R> String.flatMap(transform: (Char) -> Iterable<R>): List<R>
}
/**
* Returns a single stream of all elements streamed from results of *transform* function being invoked on each element of original stream
* Returns a single sequence of all elements from results of *transform* function being invoked on each element of original sequence
*/
public fun <T, R> Sequence<T>.flatMap(transform: (T) -> Sequence<R>): Sequence<R> {
return FlatteningSequence(this, transform)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a single stream of all elements from results of *transform* function being invoked on each element of original stream
*/
public fun <T, R> Stream<T>.flatMap(transform: (T) -> Stream<R>): Stream<R> {
return FlatteningStream(this, transform)
@@ -232,6 +241,19 @@ public inline fun <R, C : MutableCollection<in R>> String.flatMapTo(destination:
return destination
}
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original sequence, to the given *destination*
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.flatMapTo(destination: C, transform: (T) -> Sequence<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements yielded from results of *transform* function being invoked on each element of original stream, to the given *destination*
*/
@@ -313,6 +335,15 @@ public inline fun <T, K> Iterable<T>.groupBy(toKey: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), toKey)
}
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
public inline fun <T, K> Sequence<T>.groupBy(toKey: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), toKey)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a map of the elements in original collection grouped by the result of given *toKey* function
*/
@@ -447,6 +478,20 @@ public inline fun <T, K> Iterable<T>.groupByTo(map: MutableMap<K, MutableList<T>
return map
}
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
public inline fun <T, K> Sequence<T>.groupByTo(map: MutableMap<K, MutableList<T>>, toKey: (T) -> K): Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
val list = map.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return map
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends elements from original collection grouped by the result of given *toKey* function to the given *map*
*/
@@ -548,6 +593,15 @@ public inline fun <K, V, R> Map<K, V>.map(transform: (Map.Entry<K, V>) -> R): Li
return mapTo(ArrayList<R>(), transform)
}
/**
* Returns a sequence containing the results of applying the given *transform* function to each element of the original sequence
*/
public fun <T, R> Sequence<T>.map(transform: (T) -> R): Sequence<R> {
return TransformingSequence(this, transform)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing the results of applying the given *transform* function to each element of the original stream
*/
@@ -632,6 +686,15 @@ public inline fun <T, R> Iterable<T>.mapIndexed(transform: (Int, T) -> R): List<
return mapIndexedTo(ArrayList<R>(collectionSizeOrDefault(10)), transform)
}
/**
* Returns a sequence containing the results of applying the given *transform* function to each element and its index of the original sequence
*/
public fun <T, R> Sequence<T>.mapIndexed(transform: (Int, T) -> R): Sequence<R> {
return TransformingIndexedSequence(this, transform)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing the results of applying the given *transform* function to each element and its index of the original stream
*/
@@ -767,6 +830,19 @@ public inline fun <K, V, R, C : MutableCollection<in R>> Map<K, V>.mapIndexedTo(
return destination
}
/**
* Appends transformed elements and their indices of the original collection using the given *transform* function
* to the given *destination*
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapIndexedTo(destination: C, transform: (Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends transformed elements and their indices of the original collection using the given *transform* function
* to the given *destination*
@@ -803,6 +879,15 @@ public inline fun <T : Any, R> Iterable<T?>.mapNotNull(transform: (T) -> R): Lis
return mapNotNullTo(ArrayList<R>(), transform)
}
/**
* Returns a sequence containing the results of applying the given *transform* function to each non-null element of the original sequence
*/
public fun <T : Any, R> Sequence<T?>.mapNotNull(transform: (T) -> R): Sequence<R> {
return TransformingSequence(FilteringSequence(this, false, { it == null }) as Sequence<T>, transform)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing the results of applying the given *transform* function to each non-null element of the original stream
*/
@@ -836,6 +921,21 @@ public inline fun <T : Any, R, C : MutableCollection<in R>> Iterable<T?>.mapNotN
return destination
}
/**
* Appends transformed non-null elements of original collection using the given *transform* function
* to the given *destination*
*/
public inline fun <T : Any, R, C : MutableCollection<in R>> Sequence<T?>.mapNotNullTo(destination: C, transform: (T) -> R): C {
for (element in this) {
if (element != null) {
destination.add(transform(element))
}
}
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends transformed non-null elements of original collection using the given *transform* function
* to the given *destination*
@@ -959,6 +1059,18 @@ public inline fun <K, V, R, C : MutableCollection<in R>> Map<K, V>.mapTo(destina
return destination
}
/**
* Appends transformed elements of the original collection using the given *transform* function
* to the given *destination*
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapTo(destination: C, transform: (T) -> R): C {
for (item in this)
destination.add(transform(item))
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends transformed elements of the original collection using the given *transform* function
* to the given *destination*
@@ -1049,6 +1161,15 @@ public fun <T> Iterable<T>.withIndex(): Iterable<IndexedValue<T>> {
return IndexingIterable { iterator() }
}
/**
* Returns a sequence of [IndexedValue] for each element of the original sequence
*/
public fun <T> Sequence<T>.withIndex(): Sequence<IndexedValue<T>> {
return IndexingSequence(this)
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream of [IndexedValue] for each element of the original stream
*/
@@ -1153,6 +1274,17 @@ public fun <T> Iterable<T>.withIndices(): List<Pair<Int, T>> {
return mapTo(ArrayList<Pair<Int, T>>(), { index++ to it })
}
/**
* Returns a sequence containing pairs of each element of the original collection and their index
*/
deprecated("Use withIndex() instead.")
public fun <T> Sequence<T>.withIndices(): Sequence<Pair<Int, T>> {
var index = 0
return TransformingSequence(this, { index++ to it })
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing pairs of each element of the original collection and their index
*/
@@ -21,6 +21,20 @@ public fun Iterable<Int>.sum(): Int {
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Sequence<Int>.sum(): Int {
val iterator = iterator()
var sum: Int = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all elements in the collection
*/
@@ -45,6 +59,20 @@ public fun Iterable<Long>.sum(): Long {
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Sequence<Long>.sum(): Long {
val iterator = iterator()
var sum: Long = 0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all elements in the collection
*/
@@ -69,6 +97,20 @@ public fun Iterable<Double>.sum(): Double {
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Sequence<Double>.sum(): Double {
val iterator = iterator()
var sum: Double = 0.0
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all elements in the collection
*/
@@ -93,6 +135,20 @@ public fun Iterable<Float>.sum(): Float {
return sum
}
/**
* Returns the sum of all elements in the collection
*/
public fun Sequence<Float>.sum(): Float {
val iterator = iterator()
var sum: Float = 0.0f
while (iterator.hasNext()) {
sum += iterator.next()
}
return sum
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns the sum of all elements in the collection
*/
@@ -272,6 +272,17 @@ public fun <T : Comparable<T>> Iterable<T>.toSortedList(): List<T> {
return sortedList
}
/**
* Returns a sorted list of all elements
*/
public fun <T : Comparable<T>> Sequence<T>.toSortedList(): List<T> {
val sortedList = toArrayList()
java.util.Collections.sort(sortedList)
return sortedList
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a sorted list of all elements
*/
@@ -381,6 +392,18 @@ public fun <T, V : Comparable<V>> Iterable<T>.toSortedListBy(order: (T) -> V): L
return sortedList
}
/**
* Returns a sorted list of all elements, ordered by results of specified *order* function.
*/
public fun <T, V : Comparable<V>> Sequence<T>.toSortedListBy(order: (T) -> V): List<T> {
val sortedList = toArrayList()
val sortBy: Comparator<T> = compareBy(order)
java.util.Collections.sort(sortedList, sortBy)
return sortedList
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a sorted list of all elements, ordered by results of specified *order* function.
*/
@@ -0,0 +1,315 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
import java.util.Collections // TODO: it's temporary while we have java.util.Collections in js
/**
* Returns a sequence from the given collection
*/
public fun <T> Array<out T>.sequence(): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun BooleanArray.sequence(): Sequence<Boolean> {
return object : Sequence<Boolean> {
override fun iterator(): Iterator<Boolean> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun ByteArray.sequence(): Sequence<Byte> {
return object : Sequence<Byte> {
override fun iterator(): Iterator<Byte> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun CharArray.sequence(): Sequence<Char> {
return object : Sequence<Char> {
override fun iterator(): Iterator<Char> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun DoubleArray.sequence(): Sequence<Double> {
return object : Sequence<Double> {
override fun iterator(): Iterator<Double> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun FloatArray.sequence(): Sequence<Float> {
return object : Sequence<Float> {
override fun iterator(): Iterator<Float> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun IntArray.sequence(): Sequence<Int> {
return object : Sequence<Int> {
override fun iterator(): Iterator<Int> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun LongArray.sequence(): Sequence<Long> {
return object : Sequence<Long> {
override fun iterator(): Iterator<Long> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun ShortArray.sequence(): Sequence<Short> {
return object : Sequence<Short> {
override fun iterator(): Iterator<Short> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun <T> Iterable<T>.sequence(): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun <K, V> Map<K, V>.sequence(): Sequence<Map.Entry<K, V>> {
return object : Sequence<Map.Entry<K, V>> {
override fun iterator(): Iterator<Map.Entry<K, V>> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
public fun <T> Sequence<T>.sequence(): Sequence<T> {
return this
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream from the given collection
*/
public fun <T> Stream<T>.stream(): Stream<T> {
return this
}
/**
* Returns a sequence from the given collection
*/
public fun String.sequence(): Sequence<Char> {
return object : Sequence<Char> {
override fun iterator(): Iterator<Char> {
return this@sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun <T> Array<out T>.stream(): Stream<T> {
val sequence = sequence()
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun BooleanArray.stream(): Stream<Boolean> {
val sequence = sequence()
return object : Stream<Boolean> {
override fun iterator(): Iterator<Boolean> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun ByteArray.stream(): Stream<Byte> {
val sequence = sequence()
return object : Stream<Byte> {
override fun iterator(): Iterator<Byte> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun CharArray.stream(): Stream<Char> {
val sequence = sequence()
return object : Stream<Char> {
override fun iterator(): Iterator<Char> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun DoubleArray.stream(): Stream<Double> {
val sequence = sequence()
return object : Stream<Double> {
override fun iterator(): Iterator<Double> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun FloatArray.stream(): Stream<Float> {
val sequence = sequence()
return object : Stream<Float> {
override fun iterator(): Iterator<Float> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun IntArray.stream(): Stream<Int> {
val sequence = sequence()
return object : Stream<Int> {
override fun iterator(): Iterator<Int> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun LongArray.stream(): Stream<Long> {
val sequence = sequence()
return object : Stream<Long> {
override fun iterator(): Iterator<Long> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun ShortArray.stream(): Stream<Short> {
val sequence = sequence()
return object : Stream<Short> {
override fun iterator(): Iterator<Short> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun <T> Iterable<T>.stream(): Stream<T> {
val sequence = sequence()
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun <K, V> Map<K, V>.stream(): Stream<Map.Entry<K, V>> {
val sequence = sequence()
return object : Stream<Map.Entry<K, V>> {
override fun iterator(): Iterator<Map.Entry<K, V>> {
return sequence.iterator()
}
}
}
/**
* Returns a sequence from the given collection
*/
deprecated("Use sequence() instead")
public fun String.stream(): Stream<Char> {
val sequence = sequence()
return object : Stream<Char> {
override fun iterator(): Iterator<Char> {
return sequence.iterator()
}
}
}
@@ -97,6 +97,15 @@ public fun <T> Iterable<T>.toArrayList(): ArrayList<T> {
return toCollection(ArrayList<T>(collectionSizeOrDefault(10)))
}
/**
* Returns an ArrayList of all elements
*/
public fun <T> Sequence<T>.toArrayList(): ArrayList<T> {
return toCollection(ArrayList<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns an ArrayList of all elements
*/
@@ -211,6 +220,18 @@ public fun <T, C : MutableCollection<in T>> Iterable<T>.toCollection(collection:
return collection
}
/**
* Appends all elements to the given *collection*
*/
public fun <T, C : MutableCollection<in T>> Sequence<T>.toCollection(collection: C): C {
for (item in this) {
collection.add(item)
}
return collection
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements to the given *collection*
*/
@@ -301,6 +322,15 @@ public fun <T> Iterable<T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Returns a HashSet of all elements
*/
public fun <T> Sequence<T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a HashSet of all elements
*/
@@ -385,6 +415,15 @@ public fun <T> Iterable<T>.toLinkedList(): LinkedList<T> {
return toCollection(LinkedList<T>())
}
/**
* Returns a LinkedList containing all elements
*/
public fun <T> Sequence<T>.toLinkedList(): LinkedList<T> {
return toCollection(LinkedList<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a LinkedList containing all elements
*/
@@ -497,6 +536,15 @@ public fun <T> Iterable<T>.toList(): List<T> {
return toCollection(ArrayList<T>(collectionSizeOrDefault(10)))
}
/**
* Returns a List containing all elements
*/
public fun <T> Sequence<T>.toList(): List<T> {
return toCollection(ArrayList<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a List containing all elements
*/
@@ -621,6 +669,19 @@ public inline fun <T, K> Iterable<T>.toMap(selector: (T) -> K): Map<K, T> {
return result
}
/**
* Returns Map containing all the values from the given collection indexed by *selector*
*/
public inline fun <T, K> Sequence<T>.toMap(selector: (T) -> K): Map<K, T> {
val result = LinkedHashMap<K, T>()
for (element in this) {
result.put(selector(element), element)
}
return result
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns Map containing all the values from the given collection indexed by *selector*
*/
@@ -713,6 +774,15 @@ public fun <T> Iterable<T>.toSet(): Set<T> {
return toCollection(LinkedHashSet<T>())
}
/**
* Returns a Set of all elements
*/
public fun <T> Sequence<T>.toSet(): Set<T> {
return toCollection(LinkedHashSet<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a Set of all elements
*/
@@ -797,6 +867,15 @@ public fun <T> Iterable<T>.toSortedSet(): SortedSet<T> {
return toCollection(TreeSet<T>())
}
/**
* Returns a SortedSet of all elements
*/
public fun <T> Sequence<T>.toSortedSet(): SortedSet<T> {
return toCollection(TreeSet<T>())
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a SortedSet of all elements
*/
@@ -467,6 +467,15 @@ public inline fun <reified R> Iterable<*>.filterIsInstance(): List<R> {
return filterIsInstanceTo(ArrayList<R>())
}
/**
* Returns a sequence containing all elements that are instances of specified type parameter R
*/
public inline fun <reified R> Sequence<*>.filterIsInstance(): Sequence<R> {
return FilteringSequence(this, true, { it is R }) as Sequence<R>
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements that are instances of specified type parameter R
*/
@@ -488,6 +497,15 @@ public fun <R> Iterable<*>.filterIsInstance(klass: Class<R>): List<R> {
return filterIsInstanceTo(ArrayList<R>(), klass)
}
/**
* Returns a sequence containing all elements that are instances of specified class
*/
public fun <R> Sequence<*>.filterIsInstance(klass: Class<R>): Sequence<R> {
return FilteringSequence(this, true, { klass.isInstance(it) }) as Sequence<R>
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Returns a stream containing all elements that are instances of specified class
*/
@@ -511,6 +529,16 @@ public inline fun <reified R, C : MutableCollection<in R>> Iterable<*>.filterIsI
return destination
}
/**
* Appends all elements that are instances of specified type parameter R to the given *destination*
*/
public inline fun <reified R, C : MutableCollection<in R>> Sequence<*>.filterIsInstanceTo(destination: C): C {
for (element in this) if (element is R) destination.add(element)
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements that are instances of specified type parameter R to the given *destination*
*/
@@ -535,6 +563,16 @@ public fun <C : MutableCollection<in R>, R> Iterable<*>.filterIsInstanceTo(desti
return destination
}
/**
* Appends all elements that are instances of specified class to the given *destination*
*/
public fun <C : MutableCollection<in R>, R> Sequence<*>.filterIsInstanceTo(destination: C, klass: Class<R>): C {
for (element in this) if (klass.isInstance(element)) destination.add(element as R)
return destination
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends all elements that are instances of specified class to the given *destination*
*/
-150
View File
@@ -1,150 +0,0 @@
package kotlin
//
// NOTE THIS FILE IS AUTO-GENERATED by the GenerateStandardLib.kt
// See: https://github.com/JetBrains/kotlin/tree/master/libraries/stdlib
//
import java.util.*
import java.util.Collections // TODO: it's temporary while we have java.util.Collections in js
/**
* Returns a stream from the given collection
*/
public fun <T> Array<out T>.stream(): Stream<T> {
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun BooleanArray.stream(): Stream<Boolean> {
return object : Stream<Boolean> {
override fun iterator(): Iterator<Boolean> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun ByteArray.stream(): Stream<Byte> {
return object : Stream<Byte> {
override fun iterator(): Iterator<Byte> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun CharArray.stream(): Stream<Char> {
return object : Stream<Char> {
override fun iterator(): Iterator<Char> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun DoubleArray.stream(): Stream<Double> {
return object : Stream<Double> {
override fun iterator(): Iterator<Double> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun FloatArray.stream(): Stream<Float> {
return object : Stream<Float> {
override fun iterator(): Iterator<Float> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun IntArray.stream(): Stream<Int> {
return object : Stream<Int> {
override fun iterator(): Iterator<Int> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun LongArray.stream(): Stream<Long> {
return object : Stream<Long> {
override fun iterator(): Iterator<Long> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun ShortArray.stream(): Stream<Short> {
return object : Stream<Short> {
override fun iterator(): Iterator<Short> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun <T> Iterable<T>.stream(): Stream<T> {
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun <K, V> Map<K, V>.stream(): Stream<Map.Entry<K, V>> {
return object : Stream<Map.Entry<K, V>> {
override fun iterator(): Iterator<Map.Entry<K, V>> {
return this@stream.iterator()
}
}
}
/**
* Returns a stream from the given collection
*/
public fun <T> Stream<T>.stream(): Stream<T> {
return this
}
/**
* Returns a stream from the given collection
*/
public fun String.stream(): Stream<Char> {
return object : Stream<Char> {
override fun iterator(): Iterator<Char> {
return this@stream.iterator()
}
}
}
@@ -209,6 +209,28 @@ public fun <T, A : Appendable> Iterable<T>.joinTo(buffer: A, separator: String =
return buffer
}
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T, A : Appendable> Sequence<T>.joinTo(buffer: A, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): A {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
val text = if (element == null) "null" else element.toString()
buffer.append(text)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
return buffer
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
@@ -319,6 +341,17 @@ public fun <T> Iterable<T>.joinToString(separator: String = ", ", prefix: String
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated).toString()
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T> Sequence<T>.joinToString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated).toString()
}
deprecated("Migrate to using Sequence<T> and respective functions")
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
@@ -11,8 +11,16 @@ public fun <T> MutableCollection<in T>.addAll(iterable: Iterable<T>) {
}
/**
* Adds all elements of the given [stream] to this [MutableCollection].
* Adds all elements of the given [sequence] to this [MutableCollection].
*/
public fun <T> MutableCollection<in T>.addAll(sequence: Sequence<T>) {
for (item in sequence) add(item)
}
/**
* Adds all elements of the given [sequence] to this [MutableCollection].
*/
deprecated("Use Sequence<T> instead of Stream<T>")
public fun <T> MutableCollection<in T>.addAll(stream: Stream<T>) {
for (item in stream) add(item)
}
@@ -34,9 +42,17 @@ public fun <T> MutableCollection<in T>.removeAll(iterable: Iterable<T>) {
}
}
/**
* Removes all elements of the given [sequence] from this [MutableCollection].
*/
public fun <T> MutableCollection<in T>.removeAll(sequence: Sequence<T>) {
for (item in sequence) remove(item)
}
/**
* Removes all elements of the given [stream] from this [MutableCollection].
*/
deprecated("Use Sequence<T> instead of Stream<T>")
public fun <T> MutableCollection<in T>.removeAll(stream: Stream<T>) {
for (item in stream) remove(item)
}
@@ -15,8 +15,16 @@ public fun <T> Iterable<Iterable<T>>.flatten(): List<T> {
}
/**
* Returns a stream of all elements from all streams in the given stream.
* Returns a sequence of all elements from all sequences in this sequence.
*/
public fun <T> Sequence<Sequence<T>>.flatten(): Sequence<T> {
return FlatteningSequence(this, { it })
}
/**
* Returns a sequence of all elements from all sequences in this sequence.
*/
deprecated("Use Sequence<T> instead of Stream<T>")
public fun <T> Stream<Stream<T>>.flatten(): Stream<T> {
return FlatteningStream(this, { it })
}
@@ -1,13 +1,8 @@
package kotlin
import java.util.*
import java.util.NoSuchElementException
/**
* A sequence that returns values through its iterator. The values are evaluated lazily, and the sequence
* is potentially infinite.
*
* @param T the type of elements in the sequence.
*/
deprecated("Use Sequence<T> instead.")
public trait Stream<out T> {
/**
* Returns an iterator that returns the values from the sequence.
@@ -16,31 +11,55 @@ public trait Stream<out T> {
}
/**
* Creates a stream that returns the specified values.
* A sequence that returns values through its iterator. The values are evaluated lazily, and the sequence
* is potentially infinite.
*
* @param T the type of elements in the sequence.
*/
public trait Sequence<out T> : Stream<T>
public fun<T> Stream<T>.toSequence(): Sequence<T> = object : Sequence<T> {
override fun iterator(): Iterator<T> = this@toSequence.iterator()
}
deprecated("Use sequenceOf() instead")
public fun <T> streamOf(vararg elements: T): Stream<T> = elements.stream()
/**
* Creates a stream that returns all values in the specified [progression].
*/
deprecated("Use sequenceOf() instead")
public fun <T> streamOf(progression: Progression<T>): Stream<T> = object : Stream<T> {
override fun iterator(): Iterator<T> = progression.iterator()
}
/**
* A stream that returns the values from the underlying [stream] that either match or do not match
* Creates a sequence that returns the specified values.
*/
public fun <T> sequenceOf(vararg elements: T): Sequence<T> = elements.sequence()
/**
* Creates a sequence that returns all values in the specified [progression].
*/
public fun <T> sequenceOf(progression: Progression<T>): Sequence<T> = object : Sequence<T> {
override fun iterator(): Iterator<T> = progression.iterator()
}
deprecated("Use FilteringSequence<T> instead")
public class FilteringStream<T>(stream: Stream<T>, sendWhen: Boolean = true, predicate: (T) -> Boolean)
: Stream<T> by FilteringSequence<T>(stream.toSequence(), sendWhen, predicate)
/**
* A sequence that returns the values from the underlying [sequence] that either match or do not match
* the specified [predicate].
*
* @param sendWhen If `true`, values for which the predicate returns `true` are returned. Otherwise,
* values for which the predicate returns `false` are returned
* values for which the predicate returns `false` are returned
*/
public class FilteringStream<T>(private val stream: Stream<T>,
private val sendWhen: Boolean = true,
private val predicate: (T) -> Boolean
) : Stream<T> {
public class FilteringSequence<T>(private val sequence: Sequence<T>,
private val sendWhen: Boolean = true,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = stream.iterator();
val iterator = sequence.iterator();
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null
@@ -75,47 +94,61 @@ public class FilteringStream<T>(private val stream: Stream<T>,
}
}
deprecated("Use TransformingSequence<T> instead")
public class TransformingStream<T, R>(stream: Stream<T>, transformer: (T) -> R)
: Stream<R> by TransformingSequence<T, R>(stream.toSequence(), transformer)
/**
* A stream which returns the results of applying the given [transformer] function to the values
* in the underlying [stream].
* A sequence which returns the results of applying the given [transformer] function to the values
* in the underlying [sequence].
*/
public class TransformingStream<T, R>(private val stream: Stream<T>, private val transformer: (T) -> R) : Stream<R> {
public class TransformingSequence<T, R>(private val sequence: Sequence<T>, private val transformer: (T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = stream.iterator()
val iterator = sequence.iterator()
override fun next(): R {
return transformer(iterator.next())
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
deprecated("Use TransformingIndexedSequence<T> instead")
public class TransformingIndexedStream<T, R>(stream: Stream<T>, transformer: (Int, T) -> R)
: Stream<R> by TransformingIndexedSequence<T, R>(stream.toSequence(), transformer)
/**
* A stream which returns the results of applying the given [transformer] function to the values
* in the underlying [stream], where the transformer function takes the index of the value in the underlying
* stream along with the value itself.
* A sequence which returns the results of applying the given [transformer] function to the values
* in the underlying [sequence], where the transformer function takes the index of the value in the underlying
* sequence along with the value itself.
*/
public class TransformingIndexedStream<T, R>(private val stream: Stream<T>, private val transformer: (Int, T) -> R) : Stream<R> {
public class TransformingIndexedSequence<T, R>(private val sequence: Sequence<T>, private val transformer: (Int, T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = stream.iterator()
val iterator = sequence.iterator()
var index = 0
override fun next(): R {
return transformer(index++, iterator.next())
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
deprecated("Use IndexingSequence<T> instead")
public class IndexingStream<T>(stream: Stream<T>)
: Stream<IndexedValue<T>> by IndexingSequence(stream.toSequence())
/**
* A stream which combines values from the underlying [stream] with their indices and returns them as
* A sequence which combines values from the underlying [sequence] with their indices and returns them as
* [IndexedValue] objects.
*/
public class IndexingStream<T>(private val stream: Stream<T>) : Stream<IndexedValue<T>> {
public class IndexingSequence<T>(private val sequence: Sequence<T>) : Sequence<IndexedValue<T>> {
override fun iterator(): Iterator<IndexedValue<T>> = object : Iterator<IndexedValue<T>> {
val iterator = stream.iterator()
val iterator = sequence.iterator()
var index = 0
override fun next(): IndexedValue<T> {
return IndexedValue(index++, iterator.next())
@@ -127,32 +160,41 @@ public class IndexingStream<T>(private val stream: Stream<T>) : Stream<IndexedVa
}
}
deprecated("Use MergingSequence<T> instead")
public class MergingStream<T1, T2, V>(stream1: Stream<T1>, stream2: Stream<T2>, transform: (T1, T2) -> V)
: Stream<V> by MergingSequence(stream1.toSequence(), stream2.toSequence(), transform)
/**
* A stream which takes the values from two parallel underlying streams, passes them to the given
* [transform] function and returns the values returned by that function. The stream stops returning
* values as soon as one of the underlying streams stops returning values.
* A sequence which takes the values from two parallel underlying sequences, passes them to the given
* [transform] function and returns the values returned by that function. The sequence stops returning
* values as soon as one of the underlying sequences stops returning values.
*/
public class MergingStream<T1, T2, V>(private val stream1: Stream<T1>,
private val stream2: Stream<T2>,
private val transform: (T1, T2) -> V
) : Stream<V> {
public class MergingSequence<T1, T2, V>(private val sequence1: Sequence<T1>,
private val sequence2: Sequence<T2>,
private val transform: (T1, T2) -> V
) : Sequence<V> {
override fun iterator(): Iterator<V> = object : Iterator<V> {
val iterator1 = stream1.iterator()
val iterator2 = stream2.iterator()
val iterator1 = sequence1.iterator()
val iterator2 = sequence2.iterator()
override fun next(): V {
return transform(iterator1.next(), iterator2.next())
}
override fun hasNext(): Boolean {
return iterator1.hasNext() && iterator2.hasNext()
}
}
}
public class FlatteningStream<T, R>(private val stream: Stream<T>,
private val transformer: (T) -> Stream<R>
) : Stream<R> {
deprecated("Use FlatteningSequence<T> instead")
public class FlatteningStream<T, R>(stream: Stream<T>, transformer: (T) -> Stream<R>)
: Stream<R> by FlatteningSequence(stream.toSequence(), { transformer(it).toSequence() })
public class FlatteningSequence<T, R>(private val sequence: Sequence<T>,
private val transformer: (T) -> Sequence<R>
) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = stream.iterator()
val iterator = sequence.iterator()
var itemIterator: Iterator<R>? = null
override fun next(): R {
@@ -186,9 +228,13 @@ public class FlatteningStream<T, R>(private val stream: Stream<T>,
}
}
public class Multistream<T>(private val stream: Stream<Stream<T>>) : Stream<T> {
deprecated("Use MultiSequence<T> instead")
public class Multistream<T>(stream: Stream<Stream<T>>)
: Stream<T> by FlatteningSequence(stream.toSequence(), { it.toSequence() })
public class MultiSequence<T>(private val sequence: Sequence<Sequence<T>>) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = stream.iterator()
val iterator = sequence.iterator()
var itemIterator: Iterator<T>? = null
override fun next(): T {
@@ -222,13 +268,17 @@ public class Multistream<T>(private val stream: Stream<Stream<T>>) : Stream<T> {
}
}
deprecated("Use TakeSequence<T> instead")
public class TakeStream<T>(stream: Stream<T>, count: Int)
: Stream<T> by TakeSequence(stream.toSequence(), count)
/**
* A stream that returns at most [count] values from the underlying [stream], and stops returning values
* A sequence that returns at most [count] values from the underlying [sequence], and stops returning values
* as soon as that count is reached.
*/
public class TakeStream<T>(private val stream: Stream<T>,
private val count: Int
) : Stream<T> {
public class TakeSequence<T>(private val sequence: Sequence<T>,
private val count: Int
) : Sequence<T> {
{
if (count < 0)
throw IllegalArgumentException("count should be non-negative, but is $count")
@@ -236,7 +286,7 @@ public class TakeStream<T>(private val stream: Stream<T>,
override fun iterator(): Iterator<T> = object : Iterator<T> {
var left = count
val iterator = stream.iterator();
val iterator = sequence.iterator();
override fun next(): T {
if (left == 0)
@@ -251,15 +301,18 @@ public class TakeStream<T>(private val stream: Stream<T>,
}
}
deprecated("Use TakeWhileSequence<T> instead")
public class TakeWhileStream<T>(stream: Stream<T>, predicate: (T) -> Boolean) : Stream<T> by TakeWhileSequence<T>(stream.toSequence(), predicate)
/**
* A stream that returns values from the underlying [stream] while the [predicate] function returns
* A sequence that returns values from the underlying [sequence] while the [predicate] function returns
* `true`, and stops returning values once the function returns `false` for the next element.
*/
public class TakeWhileStream<T>(private val stream: Stream<T>,
private val predicate: (T) -> Boolean
) : Stream<T> {
public class TakeWhileSequence<T>(private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = stream.iterator();
val iterator = sequence.iterator();
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null
@@ -296,20 +349,24 @@ public class TakeWhileStream<T>(private val stream: Stream<T>,
}
}
deprecated("Use DropSequence<T> instead")
public class DropStream<T>(stream: Stream<T>, count: Int)
: Stream<T> by DropSequence<T>(stream.toSequence(), count)
/**
* A stream that skips the specified number of values from the underlying stream and returns
* A sequence that skips the specified number of values from the underlying [sequence] and returns
* all values after that.
*/
public class DropStream<T>(private val stream: Stream<T>,
private val count: Int
) : Stream<T> {
public class DropSequence<T>(private val sequence: Sequence<T>,
private val count: Int
) : Sequence<T> {
{
if (count < 0)
throw IllegalArgumentException("count should be non-negative, but is $count")
}
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = stream.iterator();
val iterator = sequence.iterator();
var left = count
// Shouldn't be called from constructor to avoid premature iteration
@@ -332,16 +389,19 @@ public class DropStream<T>(private val stream: Stream<T>,
}
}
deprecated("Use DropWhileSequence<T> instead")
public class DropWhileStream<T>(stream: Stream<T>, predicate: (T) -> Boolean) : Stream<T> by DropWhileSequence<T>(stream.toSequence(), predicate)
/**
* A stream that skips the values from the underlying stream while the given [predicate] returns `true` and returns
* A sequence that skips the values from the underlying [sequence] while the given [predicate] returns `true` and returns
* all values after that.
*/
public class DropWhileStream<T>(private val stream: Stream<T>,
private val predicate: (T) -> Boolean
) : Stream<T> {
public class DropWhileSequence<T>(private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = stream.iterator();
val iterator = sequence.iterator();
var dropState: Int = -1 // -1 for not dropping, 1 for nextItem, 0 for normal iteration
var nextItem: T? = null
@@ -379,10 +439,10 @@ public class DropWhileStream<T>(private val stream: Stream<T>,
}
/**
* A stream which repeatedly calls the specified [producer] function and returns its return values, until
* A sequence which repeatedly calls the specified [producer] function and returns its return values, until
* `null` is returned from [producer].
*/
public class FunctionStream<T : Any>(private val producer: () -> T?) : Stream<T> {
public class FunctionSequence<T : Any>(private val producer: () -> T?) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null
@@ -419,16 +479,21 @@ public class FunctionStream<T : Any>(private val producer: () -> T?) : Stream<T>
}
/**
* Returns a stream which invokes the function to calculate the next value on each iteration until the function returns `null`.
* Returns a sequence which invokes the function to calculate the next value on each iteration until the function returns `null`.
*/
public fun <T : Any> stream(nextFunction: () -> T?): Stream<T> {
return FunctionStream(nextFunction)
public fun <T : Any> sequence(nextFunction: () -> T?): Sequence<T> {
return FunctionSequence(nextFunction)
}
deprecated("Use sequence() instead")
public fun <T : Any> stream(nextFunction: () -> T?): Sequence<T> = sequence(nextFunction)
/**
* Returns a stream which invokes the function to calculate the next value based on the previous one on each iteration
* Returns a sequence which invokes the function to calculate the next value based on the previous one on each iteration
* until the function returns `null`.
*/
public /*inline*/ fun <T : Any> stream(initialValue: T, nextFunction: (T) -> T?): Stream<T> =
stream(nextFunction.toGenerator(initialValue))
public /*inline*/ fun <T : Any> sequence(initialValue: T, nextFunction: (T) -> T?): Sequence<T> =
sequence(nextFunction.toGenerator(initialValue))
deprecated("Use sequence() instead")
public /*inline*/ fun <T : Any> stream(initialValue: T, nextFunction: (T) -> T?): Sequence<T> = sequence(initialValue, nextFunction)
@@ -7,7 +7,7 @@ import kotlin.test.assertTrue
/**
* Returns an iterator which invokes the function to calculate the next value on each iteration until the function returns *null*
*/
deprecated("Use stream(...) function to make lazy stream of values.")
deprecated("Use sequence(...) function to make lazy sequence of values.")
public fun <T:Any> iterate(nextFunction: () -> T?) : Iterator<T> {
return FunctionIterator(nextFunction)
}
@@ -16,20 +16,20 @@ public fun <T:Any> iterate(nextFunction: () -> T?) : Iterator<T> {
* Returns an iterator which invokes the function to calculate the next value based on the previous one on each iteration
* until the function returns *null*
*/
deprecated("Use stream(...) function to make lazy stream of values.")
deprecated("Use sequence(...) function to make lazy sequence of values.")
public /*inline*/ fun <T: Any> iterate(initialValue: T, nextFunction: (T) -> T?): Iterator<T> =
iterate(nextFunction.toGenerator(initialValue))
/**
* Returns an iterator whose values are pairs composed of values produced by given pair of iterators
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T, S> Iterator<T>.zip(iterator: Iterator<S>): Iterator<Pair<T, S>> = PairIterator(this, iterator)
/**
* Returns an iterator shifted to right by the given number of elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.skip(n: Int): Iterator<T> = SkippingIterator(this, n)
deprecated("Use FilteringStream<T> instead")
@@ -52,7 +52,7 @@ public fun <T> Iterable<T>.makeString(separator: String = ", ", prefix: String =
}
deprecated("Use joinToString() instead")
public fun <T> Stream<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
public fun <T> Sequence<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated)
}
@@ -108,6 +108,6 @@ public fun <T> Iterable<T>.appendString(buffer: Appendable, separator: String =
}
deprecated("Use joinTo() instead")
public fun <T> Stream<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
public fun <T> Sequence<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit {
joinTo(buffer, separator, prefix, postfix, limit, truncated)
}
@@ -11,7 +11,7 @@ import java.util.Collections // TODO: it's temporary while we have java.util.Col
/**
* Returns *true* if all elements match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.all(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (!predicate(element)) return false
return true
@@ -20,7 +20,7 @@ public inline fun <T> Iterator<T>.all(predicate: (T) -> Boolean) : Boolean {
/**
* Returns *true* if any elements match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.any(predicate: (T) -> Boolean) : Boolean {
for (element in this) if (predicate(element)) return true
return false
@@ -31,7 +31,7 @@ public inline fun <T> Iterator<T>.any(predicate: (T) -> Boolean) : Boolean {
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.appendString(buffer: Appendable, separator: String = ", ", prefix: String ="", postfix: String = "", limit: Int = -1, truncated: String = "...") : Unit {
buffer.append(prefix)
var count = 0
@@ -49,7 +49,7 @@ public fun <T> Iterator<T>.appendString(buffer: Appendable, separator: String =
/**
* Returns the number of elements which match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.count(predicate: (T) -> Boolean) : Int {
var count = 0
for (element in this) if (predicate(element)) count++
@@ -59,7 +59,7 @@ public inline fun <T> Iterator<T>.count(predicate: (T) -> Boolean) : Int {
/**
* Returns a list containing everything but the first *n* elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.drop(n: Int) : List<T> {
return dropWhile(countTo(n))
}
@@ -67,7 +67,7 @@ public fun <T> Iterator<T>.drop(n: Int) : List<T> {
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.dropWhile(predicate: (T) -> Boolean) : List<T> {
return dropWhileTo(ArrayList<T>(), predicate)
}
@@ -75,7 +75,7 @@ public inline fun <T> Iterator<T>.dropWhile(predicate: (T) -> Boolean) : List<T>
/**
* Returns a list containing the everything but the first elements that satisfy the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, L: MutableList<in T>> Iterator<T>.dropWhileTo(result: L, predicate: (T) -> Boolean) : L {
var start = true
for (element in this) {
@@ -92,7 +92,7 @@ public inline fun <T, L: MutableList<in T>> Iterator<T>.dropWhileTo(result: L, p
/**
* Returns an iterator over elements which match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.filter(predicate: (T) -> Boolean) : Iterator<T> {
return FilterIterator<T>(this, predicate)
}
@@ -100,7 +100,7 @@ public fun <T> Iterator<T>.filter(predicate: (T) -> Boolean) : Iterator<T> {
/**
* Returns an iterator over elements which don't match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.filterNot(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) predicate: (T) -> Boolean) : Iterator<T> {
return filter {!predicate(it)}
}
@@ -108,7 +108,7 @@ public inline fun <T> Iterator<T>.filterNot(inlineOptions(InlineOption.ONLY_LOCA
/**
* Returns an iterator over non-*null* elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T:Any> Iterator<T?>.filterNotNull() : Iterator<T> {
return FilterNotNullIterator(this)
}
@@ -116,7 +116,7 @@ public fun <T:Any> Iterator<T?>.filterNotNull() : Iterator<T> {
/**
* Filters all non-*null* elements into the given list
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T:Any, C: MutableCollection<in T>> Iterator<T?>.filterNotNullTo(result: C) : C {
for (element in this) if (element != null) result.add(element)
return result
@@ -125,7 +125,7 @@ public fun <T:Any, C: MutableCollection<in T>> Iterator<T?>.filterNotNullTo(resu
/**
* Returns a list containing all elements which do not match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterNotTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (!predicate(element)) result.add(element)
return result
@@ -134,7 +134,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterNotTo(result
/**
* Filters all elements which match the given predicate into the given list
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element)
return result
@@ -143,7 +143,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.filterTo(result: C
/**
* Returns the first element which matches the given *predicate* or *null* if none matched
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T:Any> Iterator<T>.find(predicate: (T) -> Boolean) : T? {
for (element in this) if (predicate(element)) return element
return null
@@ -152,7 +152,7 @@ public inline fun <T:Any> Iterator<T>.find(predicate: (T) -> Boolean) : T? {
/**
* Returns an iterator over the concatenated results of transforming each element to one or more values
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T, R> Iterator<T>.flatMap(transform: (T) -> Iterator<R>) : Iterator<R> {
return FlatMapIterator<T, R>(this, transform)
}
@@ -160,7 +160,7 @@ public fun <T, R> Iterator<T>.flatMap(transform: (T) -> Iterator<R>) : Iterator<
/**
* Returns the result of transforming each element to one or more values which are concatenated together into a single collection
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.flatMapTo(result: C, transform: (T) -> Iterable<R>) : C {
for (element in this) {
val list = transform(element)
@@ -172,7 +172,7 @@ public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.flatMapTo(resul
/**
* Folds all elements from from left to right with the *initial* value to perform the operation on sequential pairs of elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, R> Iterator<T>.fold(initial: R, operation: (R, T) -> R) : R {
var answer = initial
for (element in this) answer = operation(answer, element)
@@ -182,7 +182,7 @@ public inline fun <T, R> Iterator<T>.fold(initial: R, operation: (R, T) -> R) :
/**
* Performs the given *operation* on each element
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit {
for (element in this) operation(element)
}
@@ -190,12 +190,12 @@ public inline fun <T> Iterator<T>.forEach(operation: (T) -> Unit) : Unit {
/**
* Groups the elements in the collection into a new [[Map]] using the supplied *toKey* function to calculate the key to group the elements by
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, K> Iterator<T>.groupBy(toKey: (T) -> K) : Map<K, List<T>> {
return groupByTo(HashMap<K, MutableList<T>>(), toKey)
}
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, K> Iterator<T>.groupByTo(result: MutableMap<K, MutableList<T>>, toKey: (T) -> K) : Map<K, MutableList<T>> {
for (element in this) {
val key = toKey(element)
@@ -210,7 +210,7 @@ public inline fun <T, K> Iterator<T>.groupByTo(result: MutableMap<K, MutableList
* If a collection could be huge you can specify a non-negative value of *limit* which will only show a subset of the collection then it will
* a special *truncated* separator (which defaults to "..."
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "...") : String {
val buffer = StringBuilder()
appendString(buffer, separator, prefix, postfix, limit, truncated)
@@ -222,7 +222,7 @@ public fun <T> Iterator<T>.makeString(separator: String = ", ", prefix: String =
/**
* Returns an iterator obtained by applying *transform*, a function transforming an object of type *T* into an object of type *R*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T, R> Iterator<T>.map(transform : (T) -> R) : Iterator<R> {
return MapIterator<T, R>(this, transform)
}
@@ -231,7 +231,7 @@ public fun <T, R> Iterator<T>.map(transform : (T) -> R) : Iterator<R> {
* Transforms each element of this collection with the given *transform* function and
* adds each return value to the given *results* collection
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.mapTo(result: C, transform : (T) -> R) : C {
for (item in this)
result.add(transform(item))
@@ -241,7 +241,7 @@ public inline fun <T, R, C: MutableCollection<in R>> Iterator<T>.mapTo(result: C
/**
* Returns the largest element or null if there are no elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T: Comparable<T>> Iterator<T>.max() : T? {
if (!hasNext()) return null
@@ -256,7 +256,7 @@ public fun <T: Comparable<T>> Iterator<T>.max() : T? {
/**
* Returns the first element yielding the largest value of the given function or null if there are no elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <R: Comparable<R>, T: Any> Iterator<T>.maxBy(f: (T) -> R) : T? {
if (!hasNext()) return null
@@ -276,7 +276,7 @@ public inline fun <R: Comparable<R>, T: Any> Iterator<T>.maxBy(f: (T) -> R) : T?
/**
* Returns the smallest element or null if there are no elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T: Comparable<T>> Iterator<T>.min() : T? {
if (!hasNext()) return null
@@ -291,7 +291,7 @@ public fun <T: Comparable<T>> Iterator<T>.min() : T? {
/**
* Returns the first element yielding the smallest value of the given function or null if there are no elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <R: Comparable<R>, T: Any> Iterator<T>.minBy(f: (T) -> R) : T? {
if (!hasNext()) return null
@@ -311,7 +311,7 @@ public inline fun <R: Comparable<R>, T: Any> Iterator<T>.minBy(f: (T) -> R) : T?
/**
* Partitions this collection into a pair of collections
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.partition(predicate: (T) -> Boolean) : Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
@@ -328,7 +328,7 @@ public inline fun <T> Iterator<T>.partition(predicate: (T) -> Boolean) : Pair<Li
/**
* Creates an [[Iterator]] which iterates over this iterator then the following collection
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.plus(collection: Iterable<T>) : Iterator<T> {
return plus(collection.iterator())
}
@@ -336,7 +336,7 @@ public fun <T> Iterator<T>.plus(collection: Iterable<T>) : Iterator<T> {
/**
* Creates an [[Iterator]] which iterates over this iterator then the given element at the end
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.plus(element: T) : Iterator<T> {
return CompositeIterator<T>(this, SingleIterator(element))
}
@@ -344,7 +344,7 @@ public fun <T> Iterator<T>.plus(element: T) : Iterator<T> {
/**
* Creates an [[Iterator]] which iterates over this iterator then the following iterator
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.plus(iterator: Iterator<T>) : Iterator<T> {
return CompositeIterator<T>(this, iterator)
}
@@ -353,7 +353,7 @@ public fun <T> Iterator<T>.plus(iterator: Iterator<T>) : Iterator<T> {
* Applies binary operation to all elements of iterable, going from left to right.
* Similar to fold function, but uses the first element as initial value
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T> Iterator<T>.reduce(operation: (T, T) -> T) : T {
val iterator = this.iterator()
if (!iterator.hasNext()) {
@@ -371,7 +371,7 @@ public inline fun <T> Iterator<T>.reduce(operation: (T, T) -> T) : T {
/**
* Returns a original Iterable containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T:Any> Iterator<T?>.requireNoNulls() : Iterator<T> {
return map<T?, T>{
if (it == null) throw IllegalArgumentException("null element in iterator $this") else it
@@ -381,7 +381,7 @@ public fun <T:Any> Iterator<T?>.requireNoNulls() : Iterator<T> {
/**
* Reverses the order the elements into a list
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.reverse() : List<T> {
val list = toCollection(ArrayList<T>())
Collections.reverse(list)
@@ -392,7 +392,7 @@ public fun <T> Iterator<T>.reverse() : List<T> {
* Copies all elements into a [[List]] and sorts it by value of compare_function(element)
* E.g. arrayList("two" to 2, "one" to 1).sortBy({it.second}) returns list sorted by second element of pair
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, R: Comparable<R>> Iterator<T>.sortBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: (T) -> R) : List<T> {
val sortedList = toCollection(ArrayList<T>())
val sortBy: Comparator<T> = comparator<T> {(x: T, y: T) ->
@@ -407,7 +407,7 @@ public inline fun <T, R: Comparable<R>> Iterator<T>.sortBy(inlineOptions(InlineO
/**
* Returns an iterator restricted to the first *n* elements
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.take(n: Int) : Iterator<T> {
var count = n
return takeWhile{ --count >= 0 }
@@ -416,7 +416,7 @@ public fun <T> Iterator<T>.take(n: Int) : Iterator<T> {
/**
* Returns an iterator restricted to the first elements that match the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.takeWhile(predicate: (T) -> Boolean) : Iterator<T> {
return TakeWhileIterator<T>(this, predicate)
}
@@ -424,7 +424,7 @@ public fun <T> Iterator<T>.takeWhile(predicate: (T) -> Boolean) : Iterator<T> {
/**
* Returns a list containing the first elements that satisfy the given *predicate*
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public inline fun <T, C: MutableCollection<in T>> Iterator<T>.takeWhileTo(result: C, predicate: (T) -> Boolean) : C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
@@ -433,7 +433,7 @@ public inline fun <T, C: MutableCollection<in T>> Iterator<T>.takeWhileTo(result
/**
* Copies all elements into the given collection
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T, C: MutableCollection<in T>> Iterator<T>.toCollection(result: C) : C {
for (element in this) result.add(element)
return result
@@ -442,7 +442,7 @@ public fun <T, C: MutableCollection<in T>> Iterator<T>.toCollection(result: C) :
/**
* Copies all elements into a [[LinkedList]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toLinkedList() : LinkedList<T> {
return toCollection(LinkedList<T>())
}
@@ -450,7 +450,7 @@ public fun <T> Iterator<T>.toLinkedList() : LinkedList<T> {
/**
* Copies all elements into a [[List]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toList() : List<T> {
return toCollection(ArrayList<T>())
}
@@ -458,7 +458,7 @@ public fun <T> Iterator<T>.toList() : List<T> {
/**
* Copies all elements into a [[ArrayList]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toArrayList() : ArrayList<T> {
return toCollection(ArrayList<T>())
}
@@ -466,7 +466,7 @@ public fun <T> Iterator<T>.toArrayList() : ArrayList<T> {
/**
* Copies all elements into a [[Set]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toSet() : Set<T> {
return toCollection(LinkedHashSet<T>())
}
@@ -474,7 +474,7 @@ public fun <T> Iterator<T>.toSet() : Set<T> {
/**
* Copies all elements into a [[HashSet]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toHashSet() : HashSet<T> {
return toCollection(HashSet<T>())
}
@@ -482,7 +482,7 @@ public fun <T> Iterator<T>.toHashSet() : HashSet<T> {
/**
* Copies all elements into a [[SortedSet]]
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.toSortedSet() : SortedSet<T> {
return toCollection(TreeSet<T>())
}
@@ -490,7 +490,7 @@ public fun <T> Iterator<T>.toSortedSet() : SortedSet<T> {
/**
* Returns an iterator of Pairs(index, data)
*/
deprecated("Replace Iterator<T> with Stream<T> by using stream() function instead of iterator()")
deprecated("Replace Iterator<T> with Sequence<T> by using sequence() function instead of iterator()")
public fun <T> Iterator<T>.withIndices() : Iterator<Pair<Int, T>> {
return IndexIterator(iterator())
}
+4 -4
View File
@@ -154,11 +154,11 @@ public fun Writer.buffered(bufferSize: Int = defaultBufferSize): BufferedWriter
public fun Reader.forEachLine(block: (String) -> Unit): Unit = useLines { lines -> lines.forEach(block) }
/**
* Calls the [block] callback giving it a stream of all the lines in this file and closes the reader once
* Calls the [block] callback giving it a sequence of all the lines in this file and closes the reader once
* the processing is complete.
* @return the value returned by [block].
*/
public inline fun <T> Reader.useLines(block: (Stream<String>) -> T): T =
public inline fun <T> Reader.useLines(block: (Sequence<String>) -> T): T =
this.buffered().use { block(it.lines()) }
/**
@@ -169,12 +169,12 @@ public inline fun <T> Reader.useLines(block: (Stream<String>) -> T): T =
*
* We suggest you try the method [useLines] instead which closes the stream when the processing is complete.
*/
public fun BufferedReader.lines(): Stream<String> = LinesStream(this)
public fun BufferedReader.lines(): Sequence<String> = LinesStream(this)
deprecated("Use lines() function which returns Stream<String>")
public fun BufferedReader.lineIterator(): Iterator<String> = lines().iterator()
private class LinesStream(private val reader: BufferedReader) : Stream<String> {
private class LinesStream(private val reader: BufferedReader) : Sequence<String> {
override fun iterator(): Iterator<String> {
return object : Iterator<String> {
private var nextValue: String? = null
@@ -131,6 +131,11 @@ public fun Array<String>.join(separator: String = ", ", prefix: String = "", pos
* If the stream could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun Sequence<String>.join(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated)
}
deprecated("Migrate to using Sequence<T> and respective functions")
public fun Stream<String>.join(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String {
return joinToString(separator, prefix, postfix, limit, truncated)
}
@@ -172,10 +172,10 @@ class ArraysTest {
expect(1) { array("cat", "dog", "bird").indexOfFirst { it.startsWith('d') } }
expect(2) { array("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } }
expect(-1) { streamOf("cat", "dog", "bird").indexOfFirst { it.contains("p") } }
expect(0) { streamOf("cat", "dog", "bird").indexOfFirst { it.startsWith('c') } }
expect(1) { streamOf("cat", "dog", "bird").indexOfFirst { it.startsWith('d') } }
expect(2) { streamOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } }
expect(-1) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.contains("p") } }
expect(0) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.startsWith('c') } }
expect(1) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.startsWith('d') } }
expect(2) { sequenceOf("cat", "dog", "bird").indexOfFirst { it.endsWith('d') } }
}
test fun lastIndexOf() {
@@ -191,11 +191,11 @@ class ArraysTest {
expect(2) { array("cat", "dog", "bird").indexOfLast { it.endsWith('d') } }
expect(3) { array("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } }
expect(-1) { streamOf("cat", "dog", "bird").indexOfLast { it.contains("p") } }
expect(0) { streamOf("cat", "dog", "bird").indexOfLast { it.startsWith('c') } }
expect(2) { streamOf("cat", "dog", "cap", "bird").indexOfLast { it.startsWith('c') } }
expect(2) { streamOf("cat", "dog", "bird").indexOfLast { it.endsWith('d') } }
expect(3) { streamOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } }
expect(-1) { sequenceOf("cat", "dog", "bird").indexOfLast { it.contains("p") } }
expect(0) { sequenceOf("cat", "dog", "bird").indexOfLast { it.startsWith('c') } }
expect(2) { sequenceOf("cat", "dog", "cap", "bird").indexOfLast { it.startsWith('c') } }
expect(2) { sequenceOf("cat", "dog", "bird").indexOfLast { it.endsWith('d') } }
expect(3) { sequenceOf("cat", "dog", "bird", "red").indexOfLast { it.endsWith('d') } }
}
test fun plus() {
@@ -376,8 +376,8 @@ class CollectionTest {
expect(2000000000000, { listOf(3000000000000, 2000000000000).min() })
expect('a', { listOf('a', 'b').min() })
expect("a", { listOf("a", "b").min() })
expect(null, { listOf<Int>().stream().min() })
expect(2, { listOf(2, 3).stream().min() })
expect(null, { listOf<Int>().sequence().min<Int>() })
expect(2, { listOf(2, 3).sequence().min<Int>() })
}
test fun max() {
@@ -387,8 +387,8 @@ class CollectionTest {
expect(3000000000000, { listOf(3000000000000, 2000000000000).max() })
expect('b', { listOf('a', 'b').max() })
expect("b", { listOf("a", "b").max() })
expect(null, { listOf<Int>().stream().max() })
expect(3, { listOf(2, 3).stream().max() })
expect(null, { listOf<Int>().sequence().max<Int>() })
expect(3, { listOf(2, 3).sequence().max<Int>() })
}
test fun minBy() {
@@ -397,8 +397,8 @@ class CollectionTest {
expect(3, { listOf(2, 3).minBy { -it } })
expect('a', { listOf('a', 'b').minBy { "x$it" } })
expect("b", { listOf("b", "abc").minBy { it.length() } })
expect(null, { listOf<Int>().stream().minBy { it } })
expect(3, { listOf(2, 3).stream().minBy { -it } })
expect(null, { listOf<Int>().sequence().minBy<Int, Int> { it } })
expect(3, { listOf(2, 3).sequence().minBy<Int, Int> { -it } })
}
test fun maxBy() {
@@ -407,8 +407,8 @@ class CollectionTest {
expect(2, { listOf(2, 3).maxBy { -it } })
expect('b', { listOf('a', 'b').maxBy { "x$it" } })
expect("abc", { listOf("b", "abc").maxBy { it.length() } })
expect(null, { listOf<Int>().stream().maxBy { it } })
expect(2, { listOf(2, 3).stream().maxBy { -it } })
expect(null, { listOf<Int>().sequence().maxBy<Int, Int> { it } })
expect(2, { listOf(2, 3).sequence().maxBy<Int, Int> { -it } })
}
test fun minByEvaluateOnce() {
@@ -416,7 +416,7 @@ class CollectionTest {
expect(1, { listOf(5, 4, 3, 2, 1).minBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(1, { listOf(5, 4, 3, 2, 1).stream().minBy { c++; it * it } })
expect(1, { listOf(5, 4, 3, 2, 1).sequence().minBy<Int, Int> { c++; it * it } })
assertEquals(5, c)
}
@@ -425,7 +425,7 @@ class CollectionTest {
expect(5, { listOf(5, 4, 3, 2, 1).maxBy { c++; it * it } })
assertEquals(5, c)
c = 0
expect(5, { listOf(5, 4, 3, 2, 1).stream().maxBy { c++; it * it } })
expect(5, { listOf(5, 4, 3, 2, 1).sequence().maxBy<Int, Int> { c++; it * it } })
assertEquals(5, c)
}
@@ -435,7 +435,7 @@ class CollectionTest {
expect(3.0) { listOf(1.0, 2.0).sum() }
expect(3000000000000) { arrayListOf<Long>(1000000000000, 2000000000000).sum() }
expect(3.0.toFloat()) { arrayListOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
expect(3.0.toFloat()) { streamOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
expect(3.0.toFloat()) { sequenceOf<Float>(1.0.toFloat(), 2.0.toFloat()).sum() }
}
test fun takeReturnsFirstNElements() {
+1 -1
View File
@@ -68,7 +68,7 @@ class MapTest {
test fun stream() {
val map = mapOf("beverage" to "beer", "location" to "Mells", "name" to "James")
val named = map.stream().filter { it.key == "name" }.single()
val named = map.sequence().filter { it.key == "name" }.single()
assertEquals("James", named.value)
}
@@ -21,7 +21,7 @@ class MutableCollectionTest {
val list = listOf("foo", "bar")
val collection = ArrayList<String>()
collection.addAll(list.stream())
collection.addAll(list.sequence())
assertEquals(list, collection)
}
@@ -0,0 +1,26 @@
package test.collections
import org.junit.Test as test
import kotlin.test.assertEquals
class SequenceJVMTest {
test fun filterIsInstance() {
val src: Sequence<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").sequence()
val intValues: Sequence<Int> = src.filterIsInstance<Int>()
assertEquals(listOf(1, 2), intValues.toArrayList())
val doubleValues: Sequence<Double> = src.filterIsInstance<Double>()
assertEquals(listOf(3.0), doubleValues.toArrayList())
val stringValues: Sequence<String> = src.filterIsInstance<String>()
assertEquals(listOf("abc", "cde"), stringValues.toArrayList())
val anyValues: Sequence<Any> = src.filterIsInstance<Any>()
assertEquals(src.toList(), anyValues.toArrayList())
val charValues: Sequence<Char> = src.filterIsInstance<Char>()
assertEquals(0, charValues.toArrayList().size())
}
}
@@ -4,12 +4,12 @@ import org.junit.Test as test
import kotlin.test.*
import java.util.*
fun fibonacci(): Stream<Int> {
fun fibonacci(): Sequence<Int> {
// fibonacci terms
var index = 0;
var a = 0;
var b = 1
return stream {
return sequence {
when (index++) { 0 -> a; 1 -> b; else -> {
val result = a + b; a = b; b = result; result
}
@@ -17,26 +17,26 @@ fun fibonacci(): Stream<Int> {
}
}
public class StreamTest {
public class SequenceTest {
test fun filterEmptyStream() {
val stream = streamOf<String>()
test fun filterEmptySequence() {
val stream = sequenceOf<String>()
assertEquals(0, stream.filter { false }.count())
assertEquals(0, stream.filter { true }.count())
}
test fun mapEmptyStream() {
val stream = streamOf<String>()
val stream = sequenceOf<String>()
assertEquals(0, stream.map { false }.count())
assertEquals(0, stream.map { true }.count())
}
test fun requireNoNulls() {
val stream = streamOf<String?>("foo", "bar")
val stream = sequenceOf<String?>("foo", "bar")
val notNull = stream.requireNoNulls()
assertEquals(listOf("foo", "bar"), notNull.toList())
val streamWithNulls = streamOf("foo", null, "bar")
val streamWithNulls = sequenceOf("foo", null, "bar")
val notNull2 = streamWithNulls.requireNoNulls() // shouldn't fail yet
fails {
// should throw an exception as we have a null
@@ -45,35 +45,35 @@ public class StreamTest {
}
test fun filterNullable() {
val data = streamOf(null, "foo", null, "bar")
val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filter { it == null || it == "foo" }
assertEquals(listOf(null, "foo", null), filtered.toList())
}
test fun filterNot() {
val data = streamOf(null, "foo", null, "bar")
val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNot { it == null }
assertEquals(listOf("foo", "bar"), filtered.toList())
}
test fun filterNotNull() {
val data = streamOf(null, "foo", null, "bar")
val data = sequenceOf(null, "foo", null, "bar")
val filtered = data.filterNotNull()
assertEquals(listOf("foo", "bar"), filtered.toList())
}
test fun mapNotNull() {
val data = streamOf(null, "foo", null, "bar")
val data = sequenceOf(null, "foo", null, "bar")
val foo = data.mapNotNull { it.length() }
assertEquals(listOf(3, 3), foo.toList())
assertTrue {
foo is Stream<Int>
foo is Sequence<Int>
}
}
test fun withIndex() {
val data = streamOf("foo", "bar")
val data = sequenceOf("foo", "bar")
val indexed = data.withIndex().map { it.value.substring(0..it.index) }.toList()
assertEquals(2, indexed.size())
assertEquals(listOf("f", "ba"), indexed)
@@ -112,12 +112,12 @@ public class StreamTest {
test fun dropWhile() {
assertEquals("233, 377, 610", fibonacci().dropWhile { it < 200 }.take(3).joinToString(limit = 10))
assertEquals("", streamOf(1).dropWhile { it < 200 }.joinToString(limit = 10))
assertEquals("", sequenceOf(1).dropWhile { it < 200 }.joinToString(limit = 10))
}
test fun merge() {
expect(listOf("ab", "bc", "cd")) {
streamOf("a", "b", "c").merge(streamOf("b", "c", "d")) { a, b -> a + b }.toList()
sequenceOf("a", "b", "c").merge(sequenceOf("b", "c", "d")) { a, b -> a + b }.toList()
}
}
@@ -128,24 +128,24 @@ public class StreamTest {
}
test fun plus() {
val stream = streamOf("foo", "bar")
val stream = sequenceOf("foo", "bar")
val streamCheese = stream + "cheese"
assertEquals(listOf("foo", "bar", "cheese"), streamCheese.toList())
// lets use a mutable variable
var mi = streamOf("a", "b")
var mi = sequenceOf("a", "b")
mi += "c"
assertEquals(listOf("a", "b", "c"), mi.toList())
}
test fun plusCollection() {
val a = streamOf("foo", "bar")
val a = sequenceOf("foo", "bar")
val b = listOf("cheese", "wine")
val stream = a + b
assertEquals(listOf("foo", "bar", "cheese", "wine"), stream.toList())
// lets use a mutable variable
var ml = streamOf("a")
var ml = sequenceOf("a")
ml += a
ml += "beer"
ml += b
@@ -156,7 +156,7 @@ public class StreamTest {
test fun iterationOverStream() {
var s = ""
for (i in streamOf(0, 1, 2, 3, 4, 5)) {
for (i in sequenceOf(0, 1, 2, 3, 4, 5)) {
s = s + i.toString()
}
assertEquals("012345", s)
@@ -165,7 +165,7 @@ public class StreamTest {
test fun streamFromFunction() {
var count = 3
val stream = stream {
val stream = sequence {
count--
if (count >= 0) count else null
}
@@ -175,18 +175,18 @@ public class StreamTest {
}
test fun streamFromFunctionWithInitialValue() {
val values = stream(3) { n -> if (n > 0) n - 1 else null }
val values = sequence(3) { n -> if (n > 0) n - 1 else null }
assertEquals(listOf(3, 2, 1, 0), values.toList())
}
private fun <T, C : MutableCollection<in T>> Stream<T>.takeWhileTo(result: C, predicate: (T) -> Boolean): C {
private fun <T, C : MutableCollection<in T>> Sequence<T>.takeWhileTo(result: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) result.add(element) else break
return result
}
test fun streamExtensions() {
val d = ArrayList<Int>()
streamOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 })
sequenceOf(0, 1, 2, 3, 4, 5).takeWhileTo(d, { i -> i < 4 })
assertEquals(4, d.size())
}
@@ -201,27 +201,27 @@ public class StreamTest {
'5' // fibonacci(10) = 55
)
assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().stream() }.take(10).toList())
assertEquals(expected, fibonacci().drop(4).flatMap { it.toString().sequence() }.take(10).toList())
}
test fun flatMap() {
val result = streamOf(1, 2).flatMap { streamOf(0..it) }
val result = sequenceOf(1, 2).flatMap { sequenceOf(0..it) }
assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
}
test fun flatMapOnEmpty() {
val result = streamOf<Int>().flatMap { streamOf(0..it) }
val result = sequenceOf<Int>().flatMap { sequenceOf(0..it) }
assertTrue(result.none())
}
test fun flatMapWithEmptyItems() {
val result = streamOf(1, 2, 4).flatMap { if (it == 2) streamOf<Int>() else streamOf(it - 1..it) }
val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf<Int>() else sequenceOf(it - 1..it) }
assertEquals(listOf(0, 1, 3, 4), result.toList())
}
test
fun flatten() {
val data = streamOf(1, 2).map { streamOf(0..it) }
val data = sequenceOf(1, 2).map { sequenceOf(0..it) }
assertEquals(listOf(0, 1, 0, 1, 2), data.flatten().toList())
}
@@ -1,26 +0,0 @@
package test.collections
import org.junit.Test as test
import kotlin.test.assertEquals
class StreamJVMTest {
test fun filterIsInstance() {
val src: Stream<Any> = listOf(1, 2, 3.toDouble(), "abc", "cde").stream()
val intValues: Stream<Int> = src.filterIsInstance<Int>()
assertEquals(listOf(1, 2), intValues.toArrayList())
val doubleValues: Stream<Double> = src.filterIsInstance<Double>()
assertEquals(listOf(3.0), doubleValues.toArrayList())
val stringValues: Stream<String> = src.filterIsInstance<String>()
assertEquals(listOf("abc", "cde"), stringValues.toArrayList())
val anyValues: Stream<Any> = src.filterIsInstance<Any>()
assertEquals(src.toList(), anyValues.toArrayList())
val charValues: Stream<Char> = src.filterIsInstance<Char>()
assertEquals(0, charValues.toArrayList().size())
}
}
@@ -10,7 +10,7 @@ class FunctionIteratorTest {
Test fun iterateOverFunction() {
var count = 3
val iter = stream<Int> {
val iter = sequence<Int> {
count--
if (count >= 0) count else null
}
@@ -20,7 +20,7 @@ class FunctionIteratorTest {
}
Test fun iterateOverFunction2() {
val values = stream<Int>(3) { n -> if (n > 0) n - 1 else null }
val values = sequence<Int>(3) { n -> if (n > 0) n - 1 else null }
assertEquals(arrayListOf(3, 2, 1, 0), values.toList())
}
}
@@ -11,7 +11,7 @@ class IteratorsJVMTest {
fun intToBinaryDigits() = { (i: Int) ->
val binary = Integer.toBinaryString(i)!!
var index = 0
stream<Char> { if (index < binary.length()) binary.get(index++) else null }
sequence<Char> { if (index < binary.length()) binary.get(index++) else null }
}
val expected = arrayListOf(
@@ -27,7 +27,7 @@ class IteratorsJVMTest {
}
test fun flatMapOnIterator() {
val result = streamOf(1, 2).flatMap { i -> (0..i).stream()}
val result = sequenceOf(1, 2).flatMap { i -> (0..i).sequence()}
assertEquals(listOf(0, 1, 0, 1, 2), result.toList())
}
}
@@ -5,10 +5,10 @@ import org.junit.Test as test
import kotlin.test.fails
import java.util.ArrayList
fun fibonacci(): Stream<Int> {
fun fibonacci(): Sequence<Int> {
// fibonacci terms
var index = 0; var a = 0; var b = 1
return stream<Int> { when (index++) { 0 -> a; 1 -> b; else -> { val result = a + b; a = b; b = result; result } } }
return sequence<Int> { when (index++) { 0 -> a; 1 -> b; else -> { val result = a + b; a = b; b = result; result } } }
}
class IteratorsTest {
@@ -39,12 +39,12 @@ class IteratorsTest {
}
test fun plus() {
val iter = arrayListOf("foo", "bar").stream()
val iter = arrayListOf("foo", "bar").sequence()
val iter2 = iter + "cheese"
assertEquals(arrayListOf("foo", "bar", "cheese"), iter2.toList())
// lets use a mutable variable
var mi = streamOf("a", "b")
var mi = sequenceOf("a", "b")
mi += "c"
assertEquals(arrayListOf("a", "b", "c"), mi.toList())
}
@@ -52,12 +52,12 @@ class IteratorsTest {
test fun plusCollection() {
val a = arrayListOf("foo", "bar")
val b = arrayListOf("cheese", "wine")
val iter = a.stream() + b.stream()
val iter = a.sequence() + b.sequence()
assertEquals(arrayListOf("foo", "bar", "cheese", "wine"), iter.toList())
// lets use a mutable variable
var ml = arrayListOf("a").stream()
ml += a.stream()
var ml = arrayListOf("a").sequence()
ml += a.sequence()
ml += "beer"
ml += b
ml += "z"
@@ -65,11 +65,11 @@ class IteratorsTest {
}
test fun requireNoNulls() {
val iter = arrayListOf<String?>("foo", "bar").stream()
val iter = arrayListOf<String?>("foo", "bar").sequence()
val notNull = iter.requireNoNulls()
assertEquals(arrayListOf("foo", "bar"), notNull.toList())
val iterWithNulls = arrayListOf("foo", null, "bar").stream()
val iterWithNulls = arrayListOf("foo", null, "bar").sequence()
val notNull2 = iterWithNulls.requireNoNulls()
fails {
// should throw an exception as we have a null
@@ -17,7 +17,7 @@ fun generateCollectionsAPI(outDir: File) {
guards().writeTo(File(outDir, "_Guards.kt")) { build() }
generators().writeTo(File(outDir, "_Generators.kt")) { build() }
strings().writeTo(File(outDir, "_Strings.kt")) { build() }
streams().writeTo(File(outDir, "_Streams.kt")) { build() }
sequences().writeTo(File(outDir, "_Sequences.kt")) { build() }
specialJVM().writeTo(File(outDir, "_SpecialJVM.kt")) { build() }
ranges().writeTo(File(outDir, "_Ranges.kt")) { build() }
@@ -26,7 +26,7 @@ fun generateCollectionsAPI(outDir: File) {
// TODO: decide if sum for byte and short is needed and how to make it work
for (numeric in listOf(PrimitiveType.Int, PrimitiveType.Long, /*Byte, Short, */ PrimitiveType.Double, PrimitiveType.Float)) {
build(builder, Iterables, numeric)
build(builder, Streams, numeric)
build(builder, Sequences, numeric)
}
for (numeric in listOf(PrimitiveType.Int, PrimitiveType.Long, PrimitiveType.Byte, PrimitiveType.Short, PrimitiveType.Double, PrimitiveType.Float)) {
@@ -192,7 +192,7 @@ fun elements(): List<GenericFunction> {
throw IndexOutOfBoundsException("Collection doesn't contain element at index")
"""
}
body(Streams) {
body(Sequences) {
"""
val iterator = iterator()
var count = 0
@@ -331,7 +331,7 @@ fun elements(): List<GenericFunction> {
}
"""
}
body(Streams) {
body(Sequences) {
"""
val iterator = iterator()
if (!iterator.hasNext())
@@ -371,7 +371,7 @@ fun elements(): List<GenericFunction> {
}
"""
}
body(Streams) {
body(Sequences) {
"""
val iterator = iterator()
if (!iterator.hasNext())
@@ -1,14 +1,14 @@
package templates
import java.util.ArrayList
import templates.Family.*
import java.util.HashSet
import java.util.HashMap
import java.io.StringReader
import java.util.ArrayList
import java.util.HashMap
import java.util.HashSet
import java.util.StringTokenizer
enum class Family {
Streams
Sequences
Iterables
Collections
Lists
@@ -21,19 +21,19 @@ enum class Family {
}
enum class PrimitiveType(val name: String) {
Boolean: PrimitiveType("Boolean")
Byte: PrimitiveType("Byte")
Char: PrimitiveType("Char")
Short: PrimitiveType("Short")
Int: PrimitiveType("Int")
Long: PrimitiveType("Long")
Float: PrimitiveType("Float")
Double: PrimitiveType("Double")
Boolean : PrimitiveType("Boolean")
Byte : PrimitiveType("Byte")
Char : PrimitiveType("Char")
Short : PrimitiveType("Short")
Int : PrimitiveType("Int")
Long : PrimitiveType("Long")
Float : PrimitiveType("Float")
Double : PrimitiveType("Double")
}
class GenericFunction(val signature: String, val keyword: String = "fun") : Comparable<GenericFunction> {
val defaultFamilies = array(Iterables, Streams, ArraysOfObjects, ArraysOfPrimitives, Strings)
val defaultFamilies = array(Iterables, Sequences, ArraysOfObjects, ArraysOfPrimitives, Strings)
var toNullableT: Boolean = false
@@ -45,7 +45,7 @@ class GenericFunction(val signature: String, val keyword: String = "fun") : Comp
private val buildPrimitives = HashSet(PrimitiveType.values().toList())
var deprecate: String = ""
val deprecates = HashMap<Family, String>()
val deprecates = hashMapOf<Family, String>()
var doc: String = ""
val docs = HashMap<Family, String>()
@@ -159,7 +159,7 @@ class GenericFunction(val signature: String, val keyword: String = "fun") : Comp
}
fun build(builder: StringBuilder, f: Family) {
if (f == ArraysOfPrimitives || f == RangesOfPrimitives || f == ProgressionsOfPrimitives) {
if (f == ArraysOfPrimitives || f == RangesOfPrimitives || f == ProgressionsOfPrimitives) {
for (primitive in buildPrimitives.sortBy { it.name() })
build(builder, f, primitive)
} else {
@@ -168,6 +168,23 @@ class GenericFunction(val signature: String, val keyword: String = "fun") : Comp
}
fun build(builder: StringBuilder, f: Family, primitive: PrimitiveType?) {
if (f == Sequences) {
val text = StringBuilder {
doBuild(this, f, primitive)
}.toString()
builder.append(text)
builder.appendln()
builder.appendln("deprecated(\"Migrate to using Sequence<T> and respective functions\")")
val streamText = text
.replace("Sequence", "Stream")
.replace("sequence", "stream")
.replace("MultiStream", "Multistream")
builder.append(streamText)
} else
doBuild(builder, f, primitive)
}
fun doBuild(builder: StringBuilder, f: Family, primitive: PrimitiveType?) {
val returnType = returnTypes[f] ?: defaultReturnType
if (returnType.isEmpty())
throw RuntimeException("No return type specified for $signature")
@@ -178,7 +195,7 @@ class GenericFunction(val signature: String, val keyword: String = "fun") : Comp
Collections -> "Collection<$isAsteriskOrT>"
Lists -> "List<$isAsteriskOrT>"
Maps -> "Map<K, V>"
Streams -> "Stream<$isAsteriskOrT>"
Sequences -> "Sequence<$isAsteriskOrT>"
ArraysOfObjects -> "Array<$isAsteriskOrT>"
Strings -> "String"
ArraysOfPrimitives -> primitive?.let { it.name() + "Array" } ?: throw IllegalArgumentException("Primitive array should specify primitive type")
@@ -301,7 +318,7 @@ class GenericFunction(val signature: String, val keyword: String = "fun") : Comp
builder.append('\n')
StringReader(body).forEachLine {
var count = indent
val line = it.dropWhile { count-- > 0 && it == ' ' } .renderType()
val line = it.dropWhile { count-- > 0 && it == ' ' }.renderType()
if (line.isNotEmpty()) {
builder.append(" ").append(line)
builder.append("\n")
@@ -19,11 +19,11 @@ fun filtering(): List<GenericFunction> {
"""
}
doc(Streams) { "Returns a stream containing all elements except first [n] elements" }
returns(Streams) { "Stream<T>" }
body(Streams) {
doc(Sequences) { "Returns a sequence containing all elements except first [n] elements" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return DropStream(this, n)
return DropSequence(this, n)
"""
}
@@ -66,11 +66,11 @@ fun filtering(): List<GenericFunction> {
body(Strings) { "return substring(0, Math.min(n, length()))" }
returns(Strings) { "String" }
doc(Streams) { "Returns a stream containing first *n* elements" }
returns(Streams) { "Stream<T>" }
body(Streams) {
doc(Sequences) { "Returns a sequence containing first *n* elements" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return TakeStream(this, n)
return TakeSequence(this, n)
"""
}
@@ -122,12 +122,12 @@ fun filtering(): List<GenericFunction> {
"""
}
inline(false, Streams)
doc(Streams) { "Returns a stream containing all elements except first elements that satisfy the given [predicate]" }
returns(Streams) { "Stream<T>" }
body(Streams) {
inline(false, Sequences)
doc(Sequences) { "Returns a sequence containing all elements except first elements that satisfy the given [predicate]" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return DropWhileStream(this, predicate)
return DropWhileSequence(this, predicate)
"""
}
@@ -162,12 +162,12 @@ fun filtering(): List<GenericFunction> {
"""
}
inline(false, Streams)
doc(Streams) { "Returns a stream containing first elements satisfying the given [predicate]" }
returns(Streams) { "Stream<T>" }
body(Streams) {
inline(false, Sequences)
doc(Sequences) { "Returns a sequence containing first elements satisfying the given [predicate]" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return TakeWhileStream(this, predicate)
return TakeWhileSequence(this, predicate)
"""
}
}
@@ -191,12 +191,12 @@ fun filtering(): List<GenericFunction> {
"""
}
inline(false, Streams)
doc(Streams) { "Returns a stream containing all elements matching the given [predicate]" }
returns(Streams) { "Stream<T>" }
body(Streams) {
inline(false, Sequences)
doc(Sequences) { "Returns a sequence containing all elements matching the given [predicate]" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return FilteringStream(this, true, predicate)
return FilteringSequence(this, true, predicate)
"""
}
}
@@ -246,12 +246,12 @@ fun filtering(): List<GenericFunction> {
"""
}
inline(false, Streams)
doc(Streams) { "Returns a stream containing all elements not matching the given [predicate]" }
returns(Streams) { "Stream<T>" }
body(Streams) {
inline(false, Sequences)
doc(Sequences) { "Returns a sequence containing all elements not matching the given [predicate]" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return FilteringStream(this, false, predicate)
return FilteringSequence(this, false, predicate)
"""
}
}
@@ -291,11 +291,11 @@ fun filtering(): List<GenericFunction> {
"""
}
doc(Streams) { "Returns a stream containing all elements that are not null" }
returns(Streams) { "Stream<T>" }
body(Streams) {
doc(Sequences) { "Returns a sequence containing all elements that are not null" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return FilteringStream(this, false, { it == null }) as Stream<T>
return FilteringSequence(this, false, { it == null }) as Sequence<T>
"""
}
}
@@ -17,17 +17,17 @@ fun generators(): List<GenericFunction> {
"""
}
doc(Streams) { "Returns a stream containing all elements of original stream and then the given element" }
returns(Streams) { "Stream<T>" }
body(Streams) {
doc(Sequences) { "Returns a sequence containing all elements of original sequence and then the given element" }
returns(Sequences) { "Sequence<T>" }
body(Sequences) {
"""
return Multistream(streamOf(this, streamOf(element)))
return MultiSequence(sequenceOf(this, sequenceOf(element)))
"""
}
}
templates add f("plus(collection: Iterable<T>)") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a list containing all elements of original collection and then all elements of the given *collection*" }
returns("List<T>")
body {
@@ -40,7 +40,7 @@ fun generators(): List<GenericFunction> {
}
templates add f("plus(array: Array<out T>)") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a list containing all elements of original collection and then all elements of the given *collection*" }
returns("List<T>")
body {
@@ -53,23 +53,23 @@ fun generators(): List<GenericFunction> {
}
templates add f("plus(collection: Iterable<T>)") {
only(Streams)
doc { "Returns a stream containing all elements of original stream and then all elements of the given *collection*" }
returns("Stream<T>")
only(Sequences)
doc { "Returns a sequence containing all elements of original sequence and then all elements of the given [collection]" }
returns("Sequence<T>")
body {
"""
return Multistream(streamOf(this, collection.stream()))
return MultiSequence(sequenceOf(this, collection.sequence()))
"""
}
}
templates add f("plus(stream: Stream<T>)") {
only(Streams)
doc { "Returns a stream containing all elements of original stream and then all elements of the given *stream*" }
returns("Stream<T>")
templates add f("plus(sequence: Sequence<T>)") {
only(Sequences)
doc { "Returns a sequence containing all elements of original sequence and then all elements of the given [sequence]" }
returns("Sequence<T>")
body {
"""
return Multistream(streamOf(this, stream))
return MultiSequence(sequenceOf(this, sequence))
"""
}
}
@@ -84,7 +84,7 @@ fun generators(): List<GenericFunction> {
while *second* collection contains elements for which predicate yielded *false*
"""
}
// TODO: Stream variant
// TODO: Sequence variant
returns("Pair<List<T>, List<T>>")
body {
"""
@@ -119,7 +119,7 @@ fun generators(): List<GenericFunction> {
}
templates add f("merge(other: Iterable<R>, transform: (T, R) -> V)") {
exclude(Streams, Strings)
exclude(Sequences, Strings)
doc {
"""
Returns a list of values built from elements of both collections with same indexes using provided *transform*. List has length of shortest collection.
@@ -154,7 +154,7 @@ fun generators(): List<GenericFunction> {
}
templates add f("merge(array: Array<out R>, transform: (T, R) -> V)") {
exclude(Streams, Strings)
exclude(Sequences, Strings)
doc {
"""
Returns a list of values built from elements of both collections with same indexes using provided *transform*. List has length of shortest collection.
@@ -190,26 +190,26 @@ fun generators(): List<GenericFunction> {
}
templates add f("merge(stream: Stream<R>, transform: (T, R) -> V)") {
only(Streams)
templates add f("merge(sequence: Sequence<R>, transform: (T, R) -> V)") {
only(Sequences)
doc {
"""
Returns a stream of values built from elements of both collections with same indexes using provided *transform*. Stream has length of shortest stream.
Returns a sequence of values built from elements of both collections with same indexes using provided *transform*. Resulting sequence has length of shortest input sequences.
"""
}
typeParam("R")
typeParam("V")
returns("Stream<V>")
returns("Sequence<V>")
body {
"""
return MergingStream(this, stream, transform)
return MergingSequence(this, sequence, transform)
"""
}
}
templates add f("zip(other: Iterable<R>)") {
exclude(Streams, Strings)
exclude(Sequences, Strings)
doc {
"""
Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
@@ -246,7 +246,7 @@ fun generators(): List<GenericFunction> {
}
templates add f("zip(array: Array<out R>)") {
exclude(Streams, Strings)
exclude(Sequences, Strings)
doc {
"""
Returns a list of pairs built from elements of both collections with same indexes. List has length of shortest collection.
@@ -261,18 +261,19 @@ fun generators(): List<GenericFunction> {
}
}
templates add f("zip(stream: Stream<R>)") {
only(Streams)
templates add f("zip(sequence: Sequence<R>)") {
only(Sequences)
doc {
"""
Returns a stream of pairs built from elements of both collections with same indexes. Stream has length of shortest stream.
Returns a sequence of pairs built from elements of both collections with same indexes.
Resulting sequence has length of shortest input sequences.
"""
}
typeParam("R")
returns("Stream<Pair<T, R>>")
returns("Sequence<Pair<T, R>>")
body {
"""
return MergingStream(this, stream) { (t1, t2) -> t1 to t2 }
return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 }
"""
}
}
@@ -25,14 +25,14 @@ fun guards(): List<GenericFunction> {
return this as SELF
"""
}
body(Streams) {
body(Sequences) {
"""
return FilteringStream(this) {
return FilteringSequence(this) {
if (it == null) {
throw IllegalArgumentException("null element found in $THIS")
}
true
} as Stream<T>
} as Sequence<T>
"""
}
}
@@ -16,12 +16,12 @@ fun mapping(): List<GenericFunction> {
"""
}
returns(Streams) { "Stream<Pair<Int, T>>" }
doc(Streams) { "Returns a stream containing pairs of each element of the original collection and their index" }
body(Streams) {
returns(Sequences) { "Sequence<Pair<Int, T>>" }
doc(Sequences) { "Returns a sequence containing pairs of each element of the original collection and their index" }
body(Sequences) {
"""
var index = 0
return TransformingStream(this, { index++ to it })
return TransformingSequence(this, { index++ to it })
"""
}
}
@@ -35,11 +35,11 @@ fun mapping(): List<GenericFunction> {
"""
}
returns(Streams) { "Stream<IndexedValue<T>>" }
doc(Streams) { "Returns a stream of [IndexedValue] for each element of the original stream" }
body(Streams) {
returns(Sequences) { "Sequence<IndexedValue<T>>" }
doc(Sequences) { "Returns a sequence of [IndexedValue] for each element of the original sequence" }
body(Sequences) {
"""
return IndexingStream(this)
return IndexingSequence(this)
"""
}
}
@@ -59,11 +59,11 @@ fun mapping(): List<GenericFunction> {
body(Strings) {
"return mapIndexedTo(ArrayList<R>(length()), transform)"
}
inline(false, Streams)
returns(Streams) { "Stream<R>" }
doc(Streams) { "Returns a stream containing the results of applying the given *transform* function to each element and its index of the original stream" }
body(Streams) {
"return TransformingIndexedStream(this, transform)"
inline(false, Sequences)
returns(Sequences) { "Sequence<R>" }
doc(Sequences) { "Returns a sequence containing the results of applying the given *transform* function to each element and its index of the original sequence" }
body(Sequences) {
"return TransformingIndexedSequence(this, transform)"
}
}
@@ -77,11 +77,11 @@ fun mapping(): List<GenericFunction> {
"return mapTo(ArrayList<R>(), transform)"
}
inline(false, Streams)
returns(Streams) { "Stream<R>" }
doc(Streams) { "Returns a stream containing the results of applying the given *transform* function to each element of the original stream" }
body(Streams) {
"return TransformingStream(this, transform)"
inline(false, Sequences)
returns(Sequences) { "Sequence<R>" }
doc(Sequences) { "Returns a sequence containing the results of applying the given *transform* function to each element of the original sequence" }
body(Sequences) {
"return TransformingSequence(this, transform)"
}
include(Maps)
}
@@ -100,12 +100,12 @@ fun mapping(): List<GenericFunction> {
"""
}
doc(Streams) { "Returns a stream containing the results of applying the given *transform* function to each non-null element of the original stream" }
returns(Streams) { "Stream<R>" }
inline(false, Streams)
body(Streams) {
doc(Sequences) { "Returns a sequence containing the results of applying the given *transform* function to each non-null element of the original sequence" }
returns(Sequences) { "Sequence<R>" }
inline(false, Sequences)
body(Sequences) {
"""
return TransformingStream(FilteringStream(this, false, { it == null }) as Stream<T>, transform)
return TransformingSequence(FilteringSequence(this, false, { it == null }) as Sequence<T>, transform)
"""
}
}
@@ -186,7 +186,7 @@ fun mapping(): List<GenericFunction> {
templates add f("flatMap(transform: (T) -> Iterable<R>)") {
inline(true)
exclude(Streams)
exclude(Sequences)
doc { "Returns a single list of all elements yielded from results of *transform* function being invoked on each element of original collection" }
typeParam("R")
returns("List<R>")
@@ -196,19 +196,19 @@ fun mapping(): List<GenericFunction> {
include(Maps)
}
templates add f("flatMap(transform: (T) -> Stream<R>)") {
only(Streams)
doc { "Returns a single stream of all elements streamed from results of *transform* function being invoked on each element of original stream" }
templates add f("flatMap(transform: (T) -> Sequence<R>)") {
only(Sequences)
doc { "Returns a single sequence of all elements from results of *transform* function being invoked on each element of original sequence" }
typeParam("R")
returns("Stream<R>")
returns("Sequence<R>")
body {
"return FlatteningStream(this, transform)"
"return FlatteningSequence(this, transform)"
}
}
templates add f("flatMapTo(destination: C, transform: (T) -> Iterable<R>)") {
inline(true)
exclude(Streams)
exclude(Sequences)
doc { "Appends all elements yielded from results of *transform* function being invoked on each element of original collection, to the given *destination*" }
typeParam("R")
typeParam("C : MutableCollection<in R>")
@@ -225,11 +225,11 @@ fun mapping(): List<GenericFunction> {
include(Maps)
}
templates add f("flatMapTo(destination: C, transform: (T) -> Stream<R>)") {
templates add f("flatMapTo(destination: C, transform: (T) -> Sequence<R>)") {
inline(true)
only(Streams)
doc { "Appends all elements yielded from results of *transform* function being invoked on each element of original stream, to the given *destination*" }
only(Sequences)
doc { "Appends all elements yielded from results of *transform* function being invoked on each element of original sequence, to the given *destination*" }
typeParam("R")
typeParam("C : MutableCollection<in R>")
returns("C")
@@ -25,7 +25,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
}
templates add f("sort()") {
@@ -44,7 +44,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
exclude(ArraysOfPrimitives)
exclude(ArraysOfObjects)
exclude(Strings)
@@ -66,7 +66,7 @@ fun ordering(): List<GenericFunction> {
"""
}
only(Streams, ArraysOfObjects, ArraysOfPrimitives, Iterables)
only(Sequences, ArraysOfObjects, ArraysOfPrimitives, Iterables)
}
templates add f("sortDescending()") {
@@ -85,7 +85,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
exclude(ArraysOfPrimitives)
exclude(ArraysOfObjects)
exclude(Strings)
@@ -110,7 +110,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
exclude(ArraysOfPrimitives)
exclude(Strings)
}
@@ -133,7 +133,7 @@ fun ordering(): List<GenericFunction> {
"""
}
only(Streams, ArraysOfObjects, ArraysOfPrimitives, Iterables)
only(Sequences, ArraysOfObjects, ArraysOfPrimitives, Iterables)
}
templates add f("sortDescendingBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) order: (T) -> R)") {
@@ -155,7 +155,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
exclude(ArraysOfPrimitives)
exclude(Strings)
}
@@ -175,7 +175,7 @@ fun ordering(): List<GenericFunction> {
"""
}
exclude(Streams)
exclude(Sequences)
exclude(ArraysOfPrimitives)
exclude(Strings)
}
@@ -0,0 +1,50 @@
package templates
import templates.Family.*
fun sequences(): List<GenericFunction> {
val templates = arrayListOf<GenericFunction>()
templates add f("stream()") {
include(Maps)
exclude(Sequences)
deprecate { "Use sequence() instead" }
doc { "Returns a sequence from the given collection" }
returns("Stream<T>")
body {
"""
val sequence = sequence()
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return sequence.iterator()
}
}
"""
}
}
templates add f("sequence()") {
include(Maps)
exclude(Sequences)
doc { "Returns a sequence from the given collection" }
returns("Sequence<T>")
body {
"""
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
return this@sequence.iterator()
}
}
"""
}
body(Sequences) {
"""
return this
"""
}
}
return templates
}
@@ -6,7 +6,7 @@ fun sets(): List<GenericFunction> {
val templates = arrayListOf<GenericFunction>()
templates add f("toMutableSet()") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a mutable set containing all distinct elements from the given collection." }
returns("MutableSet<T>")
body {
@@ -27,7 +27,7 @@ fun sets(): List<GenericFunction> {
}
templates add f("distinct()") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a set containing all distinct elements from the given collection." }
returns("Set<T>")
@@ -39,7 +39,7 @@ fun sets(): List<GenericFunction> {
}
templates add f("union(other: Iterable<T>)") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a set containing all distinct elements from both collections." }
returns("Set<T>")
body {
@@ -52,7 +52,7 @@ fun sets(): List<GenericFunction> {
}
templates add f("intersect(other: Iterable<T>)") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a set containing all distinct elements from both collections." }
returns("Set<T>")
body {
@@ -65,7 +65,7 @@ fun sets(): List<GenericFunction> {
}
templates add f("subtract(other: Iterable<T>)") {
exclude(Strings, Streams)
exclude(Strings, Sequences)
doc { "Returns a set containing all distinct elements from both collections." }
returns("Set<T>")
body {
@@ -41,7 +41,7 @@ fun snapshots(): List<GenericFunction> {
doc { "Returns an ArrayList of all elements" }
returns("ArrayList<T>")
body { "return toCollection(ArrayList<T>(collectionSizeOrDefault(10)))" }
body(Streams) { "return toCollection(ArrayList<T>())" }
body(Sequences) { "return toCollection(ArrayList<T>())" }
body(Strings) { "return toCollection(ArrayList<T>(length()))" }
body(ArraysOfObjects, ArraysOfPrimitives) {
"""
@@ -70,7 +70,7 @@ fun snapshots(): List<GenericFunction> {
doc { "Returns a List containing all elements" }
returns("List<T>")
body { "return toCollection(ArrayList<T>(collectionSizeOrDefault(10)))" }
body(Streams) { "return toCollection(ArrayList<T>())" }
body(Sequences) { "return toCollection(ArrayList<T>())" }
body(Strings) { "return toCollection(ArrayList<T>(length()))" }
body(ArraysOfObjects, ArraysOfPrimitives) {
"""
@@ -102,11 +102,11 @@ fun specialJVM(): List<GenericFunction> {
}
exclude(ArraysOfPrimitives, Strings)
doc(Streams) { "Returns a stream containing all elements that are instances of specified class" }
returns(Streams) { "Stream<R>" }
body(Streams) {
doc(Sequences) { "Returns a sequence containing all elements that are instances of specified class" }
returns(Sequences) { "Sequence<R>" }
body(Sequences) {
"""
return FilteringStream(this, true, { klass.isInstance(it) }) as Stream<R>
return FilteringSequence(this, true, { klass.isInstance(it) }) as Sequence<R>
"""
}
}
@@ -140,13 +140,13 @@ fun specialJVM(): List<GenericFunction> {
}
exclude(ArraysOfPrimitives, Strings)
doc(Streams) { "Returns a stream containing all elements that are instances of specified type parameter R" }
returns(Streams) { "Stream<R>" }
doc(Sequences) { "Returns a sequence containing all elements that are instances of specified type parameter R" }
returns(Sequences) { "Sequence<R>" }
inline(true)
receiverAsterisk(true)
body(Streams) {
body(Sequences) {
"""
return FilteringStream(this, true, { it is R }) as Stream<R>
return FilteringSequence(this, true, { it is R }) as Sequence<R>
"""
}
}
@@ -1,30 +0,0 @@
package templates
import templates.Family.*
fun streams(): List<GenericFunction> {
val templates = arrayListOf<GenericFunction>()
templates add f("stream()") {
include(Maps)
doc { "Returns a stream from the given collection" }
returns("Stream<T>")
body {
"""
return object : Stream<T> {
override fun iterator(): Iterator<T> {
return this@stream.iterator()
}
}
"""
}
body(Streams) {
"""
return this
"""
}
}
return templates
}