From e448f40756f004105693811e615219306ea0eaf7 Mon Sep 17 00:00:00 2001 From: Ilya Ryzhenkov Date: Tue, 10 Mar 2015 18:10:57 +0300 Subject: [PATCH] Rename Stream to Sequence and provide migration path via deprecated types and functions. --- .../ConvertToConcatenatedStringIntention.kt | 8 +- .../gotoSymbol/stdLibJoinToString.kt | 1 + .../js/test/semantics/StdLibTestToJSTest.java | 2 +- libraries/stdlib/src/generated/_Aggregates.kt | 217 ++++++++++++ libraries/stdlib/src/generated/_Elements.kt | 302 +++++++++++++++++ libraries/stdlib/src/generated/_Filtering.kt | 93 ++++++ libraries/stdlib/src/generated/_Generators.kt | 75 ++++- libraries/stdlib/src/generated/_Guards.kt | 14 + libraries/stdlib/src/generated/_Mapping.kt | 134 +++++++- libraries/stdlib/src/generated/_Numeric.kt | 56 ++++ libraries/stdlib/src/generated/_Ordering.kt | 23 ++ libraries/stdlib/src/generated/_Sequences.kt | 315 ++++++++++++++++++ libraries/stdlib/src/generated/_Snapshots.kt | 79 +++++ libraries/stdlib/src/generated/_SpecialJVM.kt | 38 +++ libraries/stdlib/src/generated/_Streams.kt | 150 --------- libraries/stdlib/src/generated/_Strings.kt | 33 ++ .../kotlin/collections/MutableCollections.kt | 18 +- .../src/kotlin/collections/Operations.kt | 10 +- .../collections/{Stream.kt => Sequence.kt} | 211 ++++++++---- .../stdlib/src/kotlin/deprecated/Iterators.kt | 8 +- .../stdlib/src/kotlin/deprecated/Strings.kt | 4 +- .../src/kotlin/deprecated/_Iterators.kt | 92 ++--- libraries/stdlib/src/kotlin/io/ReadWrite.kt | 8 +- libraries/stdlib/src/kotlin/text/Strings.kt | 5 + .../stdlib/test/collections/ArraysTest.kt | 18 +- .../stdlib/test/collections/CollectionTest.kt | 22 +- libraries/stdlib/test/collections/MapTest.kt | 2 +- .../collections/MutableCollectionsTest.kt | 2 +- .../test/collections/SequenceJVMTest.kt | 26 ++ .../{StreamTest.kt => SequenceTest.kt} | 60 ++-- .../stdlib/test/collections/StreamJVMTest.kt | 26 -- .../test/iterators/FunctionIteratorTest.kt | 4 +- .../stdlib/test/iterators/IteratorsJVMTest.kt | 4 +- .../stdlib/test/iterators/IteratorsTest.kt | 18 +- .../src/generators/GenerateCollections.kt | 4 +- .../src/templates/Elements.kt | 6 +- .../kotlin-stdlib-gen/src/templates/Engine.kt | 51 ++- .../src/templates/Filtering.kt | 64 ++-- .../src/templates/Generators.kt | 61 ++-- .../kotlin-stdlib-gen/src/templates/Guards.kt | 6 +- .../src/templates/Mapping.kt | 66 ++-- .../src/templates/Ordering.kt | 16 +- .../src/templates/Sequence.kt | 50 +++ .../kotlin-stdlib-gen/src/templates/Sets.kt | 10 +- .../src/templates/Snapshots.kt | 4 +- .../src/templates/SpecialJVM.kt | 16 +- .../kotlin-stdlib-gen/src/templates/Stream.kt | 30 -- 47 files changed, 1906 insertions(+), 556 deletions(-) create mode 100644 libraries/stdlib/src/generated/_Sequences.kt delete mode 100644 libraries/stdlib/src/generated/_Streams.kt rename libraries/stdlib/src/kotlin/collections/{Stream.kt => Sequence.kt} (55%) create mode 100644 libraries/stdlib/test/collections/SequenceJVMTest.kt rename libraries/stdlib/test/collections/{StreamTest.kt => SequenceTest.kt} (79%) delete mode 100644 libraries/stdlib/test/collections/StreamJVMTest.kt create mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Sequence.kt delete mode 100644 libraries/tools/kotlin-stdlib-gen/src/templates/Stream.kt diff --git a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt index b18ec5f7fff..c518e1dd3e7 100644 --- a/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt +++ b/idea/src/org/jetbrains/kotlin/idea/intentions/ConvertToConcatenatedStringIntention.kt @@ -40,12 +40,10 @@ public class ConvertToConcatenatedStringIntention : JetSelfTargetingIntention - 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) diff --git a/idea/testData/navigation/gotoSymbol/stdLibJoinToString.kt b/idea/testData/navigation/gotoSymbol/stdLibJoinToString.kt index 45b125aeefb..3167daebc48 100644 --- a/idea/testData/navigation/gotoSymbol/stdLibJoinToString.kt +++ b/idea/testData/navigation/gotoSymbol/stdLibJoinToString.kt @@ -10,5 +10,6 @@ // REF: (for IntArray in kotlin).joinToString(String,String,String,Int,String) // REF: (for Iterable in kotlin).joinToString(String,String,String,Int,String) // REF: (for LongArray in kotlin).joinToString(String,String,String,Int,String) +// REF: (for Sequence in kotlin).joinToString(String,String,String,Int,String) // REF: (for ShortArray in kotlin).joinToString(String,String,String,Int,String) // REF: (for Stream in kotlin).joinToString(String,String,String,Int,String) \ No newline at end of file diff --git a/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/StdLibTestToJSTest.java b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/StdLibTestToJSTest.java index f10cee18ad9..5dd2568e703 100644 --- a/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/StdLibTestToJSTest.java +++ b/js/js.tests/test/org/jetbrains/kotlin/js/test/semantics/StdLibTestToJSTest.java @@ -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" diff --git a/libraries/stdlib/src/generated/_Aggregates.kt b/libraries/stdlib/src/generated/_Aggregates.kt index adcdb6df42f..3c50daa19c4 100644 --- a/libraries/stdlib/src/generated/_Aggregates.kt +++ b/libraries/stdlib/src/generated/_Aggregates.kt @@ -97,6 +97,16 @@ public inline fun Map.all(predicate: (Map.Entry) -> Boolean): return true } +/** + * Returns *true* if all elements match the given *predicate* + */ +public inline fun Sequence.all(predicate: (T) -> Boolean): Boolean { + for (element in this) if (!predicate(element)) return false + return true +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns *true* if all elements match the given *predicate* */ @@ -201,6 +211,16 @@ public fun Map.any(): Boolean { return false } +/** + * Returns *true* if collection has at least one element + */ +public fun Sequence.any(): Boolean { + for (element in this) return true + return false +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns *true* if collection has at least one element */ @@ -305,6 +325,16 @@ public inline fun Map.any(predicate: (Map.Entry) -> Boolean): return false } +/** + * Returns *true* if any element matches the given [predicate] + */ +public inline fun Sequence.any(predicate: (T) -> Boolean): Boolean { + for (element in this) if (predicate(element)) return true + return false +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns *true* if any element matches the given [predicate] */ @@ -407,6 +437,17 @@ public fun Map.count(): Int { return size() } +/** + * Returns the number of elements + */ +public fun Sequence.count(): Int { + var count = 0 + for (element in this) count++ + return count +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the number of elements */ @@ -522,6 +563,17 @@ public inline fun Map.count(predicate: (Map.Entry) -> Boolean return count } +/** + * Returns the number of elements matching the given [predicate] + */ +public inline fun Sequence.count(predicate: (T) -> Boolean): Int { + var count = 0 + for (element in this) if (predicate(element)) count++ + return count +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the number of elements matching the given [predicate] */ @@ -630,6 +682,17 @@ public inline fun Iterable.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 Sequence.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 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 Map.forEach(operation: (Map.Entry) -> Unit) for (element in this) operation(element) } +/** + * Performs the given *operation* on each element + */ +public inline fun Sequence.forEach(operation: (T) -> Unit): Unit { + for (element in this) operation(element) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Performs the given *operation* on each element */ @@ -951,6 +1023,16 @@ public inline fun Iterable.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 Sequence.forEachIndexed(operation: (Int, T) -> Unit): Unit { + var index = 0 + for (item in this) operation(index++, item) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Performs the given *operation* on each element, providing sequential index with the element */ @@ -1085,6 +1167,22 @@ public fun > Iterable.max(): T? { return max } +/** + * Returns the largest element or null if there are no elements + */ +public fun > Sequence.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 and respective functions") /** * Returns the largest element or null if there are no elements */ @@ -1294,6 +1392,27 @@ public inline fun , T : Any> Iterable.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 , T : Any> Sequence.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 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 > Iterable.min(): T? { return min } +/** + * Returns the smallest element or null if there are no elements + */ +public fun > Sequence.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 and respective functions") /** * Returns the smallest element or null if there are no elements */ @@ -1678,6 +1813,27 @@ public inline fun , T : Any> Iterable.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 , T : Any> Sequence.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 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 Map.none(): Boolean { return true } +/** + * Returns *true* if collection has no elements + */ +public fun Sequence.none(): Boolean { + for (element in this) return false + return true +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns *true* if collection has no elements */ @@ -1927,6 +2093,16 @@ public inline fun Map.none(predicate: (Map.Entry) -> Boolean) return true } +/** + * Returns *true* if no elements match the given *predicate* + */ +public inline fun Sequence.none(predicate: (T) -> Boolean): Boolean { + for (element in this) if (predicate(element)) return false + return true +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns *true* if no elements match the given *predicate* */ @@ -2073,6 +2249,21 @@ public inline fun Iterable.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 Sequence.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 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 Iterable.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 Sequence.sumBy(transform: (T) -> Int): Int { + var sum: Int = 0 + for (element in this) { + sum += transform(element) + } + return sum +} + + +deprecated("Migrate to using Sequence 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 Iterable.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 Sequence.sumByDouble(transform: (T) -> Double): Double { + var sum: Double = 0.0 + for (element in this) { + sum += transform(element) + } + return sum +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the sum of all values produced by [transform] function from elements in the collection */ diff --git a/libraries/stdlib/src/generated/_Elements.kt b/libraries/stdlib/src/generated/_Elements.kt index 003fe8b7d96..3582b061ad4 100644 --- a/libraries/stdlib/src/generated/_Elements.kt +++ b/libraries/stdlib/src/generated/_Elements.kt @@ -431,6 +431,17 @@ public fun Iterable.contains(element: T): Boolean { return indexOf(element) >= 0 } +/** + * Returns true if *element* is found in the collection + */ +public fun Sequence.contains(element: T): Boolean { + if (this is Collection<*>) + return contains(element) + return indexOf(element) >= 0 +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns true if *element* is found in the collection */ @@ -526,6 +537,22 @@ public fun List.elementAt(index: Int): T { return get(index) } +/** + * Returns element at given *index* + */ +public fun Sequence.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 and respective functions") /** * Returns element at given *index* */ @@ -668,6 +695,29 @@ public fun List.first(): T { return this[0] } +/** + * Returns first element. + * @throws NoSuchElementException if the collection is empty. + */ +public fun Sequence.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 and respective functions") /** * Returns first element. * @throws NoSuchElementException if the collection is empty. @@ -793,6 +843,17 @@ public inline fun Iterable.first(predicate: (T) -> Boolean): T { * Returns the first element matching the given [predicate]. * @throws NoSuchElementException if no such element is found. */ +public inline fun Sequence.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 and respective functions") +/** + * "Returns the first element matching the given [predicate]. + * @throws NoSuchElementException if no such element is found. + */ public inline fun Stream.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 List.firstOrNull(): T? { return if (isEmpty()) null else this[0] } +/** + * Returns the first element, or null if the collection is empty. + */ +public fun Sequence.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 and respective functions") /** * Returns the first element, or null if the collection is empty. */ @@ -1007,6 +1090,16 @@ public inline fun Iterable.firstOrNull(predicate: (T) -> Boolean): T? { /** * Returns the first element matching the given [predicate], or `null` if element was not found */ +public inline fun Sequence.firstOrNull(predicate: (T) -> Boolean): T? { + for (element in this) if (predicate(element)) return element + return null +} + + +deprecated("Migrate to using Sequence and respective functions") +/** + * Returns first element matching the given [predicate], or `null` if element was not found + */ public inline fun Stream.firstOrNull(predicate: (T) -> Boolean): T? { for (element in this) if (predicate(element)) return element return null @@ -1149,6 +1242,21 @@ public fun Iterable.indexOf(element: T): Int { return -1 } +/** + * Returns first index of [element], or -1 if the collection does not contain element + */ +public fun Sequence.indexOf(element: T): Int { + var index = 0 + for (item in this) { + if (element == item) + return index + index++ + } + return -1 +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns first index of [element], or -1 if the collection does not contain element */ @@ -1295,6 +1403,21 @@ public inline fun List.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 Sequence.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 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 List.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 Sequence.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 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 List.last(): T { return this[lastIndex] } +/** + * Returns the last element. + * @throws NoSuchElementException if the collection is empty. + */ +public fun Sequence.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 and respective functions") /** * Returns the last element. * @throws NoSuchElementException if the collection is empty. @@ -1798,6 +1953,25 @@ public inline fun Iterable.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 Sequence.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 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 Iterable.lastIndexOf(element: T): Int { return lastIndex } +/** + * Returns last index of *element*, or -1 if the collection does not contain element + */ +public fun Sequence.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 and respective functions") /** * Returns last index of *element*, or -1 if the collection does not contain element */ @@ -2064,6 +2254,21 @@ public fun List.lastOrNull(): T? { return if (isEmpty()) null else this[size() - 1] } +/** + * Returns the last element, or `null` if the collection is empty + */ +public fun Sequence.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 and respective functions") /** * Returns the last element, or `null` if the collection is empty */ @@ -2214,6 +2419,21 @@ public inline fun Iterable.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 Sequence.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 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 List.single(): T { } } +/** + * Returns the single element, or throws an exception if the collection is empty or has more than one element. + */ +public fun Sequence.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 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 Iterable.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 Sequence.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 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 List.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 Sequence.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 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 Iterable.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 Sequence.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 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 */ diff --git a/libraries/stdlib/src/generated/_Filtering.kt b/libraries/stdlib/src/generated/_Filtering.kt index 80cae797157..dee8dcb45c1 100644 --- a/libraries/stdlib/src/generated/_Filtering.kt +++ b/libraries/stdlib/src/generated/_Filtering.kt @@ -161,6 +161,15 @@ public fun Iterable.drop(n: Int): List { return list } +/** + * Returns a sequence containing all elements except first [n] elements + */ +public fun Sequence.drop(n: Int): Sequence { + return DropSequence(this, n) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements except first [n] elements */ @@ -335,6 +344,15 @@ public inline fun Iterable.dropWhile(predicate: (T) -> Boolean): List return list } +/** + * Returns a sequence containing all elements except first elements that satisfy the given [predicate] + */ +public fun Sequence.dropWhile(predicate: (T) -> Boolean): Sequence { + return DropWhileSequence(this, predicate) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements except first elements that satisfy the given [predicate] */ @@ -423,6 +441,15 @@ public inline fun Iterable.filter(predicate: (T) -> Boolean): List { return filterTo(ArrayList(), predicate) } +/** + * Returns a sequence containing all elements matching the given [predicate] + */ +public fun Sequence.filter(predicate: (T) -> Boolean): Sequence { + return FilteringSequence(this, true, predicate) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements matching the given [predicate] */ @@ -507,6 +534,15 @@ public inline fun Iterable.filterNot(predicate: (T) -> Boolean): List return filterNotTo(ArrayList(), predicate) } +/** + * Returns a sequence containing all elements not matching the given [predicate] + */ +public fun Sequence.filterNot(predicate: (T) -> Boolean): Sequence { + return FilteringSequence(this, false, predicate) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements not matching the given [predicate] */ @@ -535,6 +571,15 @@ public fun Iterable.filterNotNull(): List { return filterNotNullTo(ArrayList()) } +/** + * Returns a sequence containing all elements that are not null + */ +public fun Sequence.filterNotNull(): Sequence { + return FilteringSequence(this, false, { it == null }) as Sequence +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements that are not null */ @@ -558,6 +603,16 @@ public fun , T : Any> Iterable.filterNotNullTo(d return destination } +/** + * Appends all elements that are not null to the given [destination] + */ +public fun , T : Any> Sequence.filterNotNullTo(destination: C): C { + for (element in this) if (element != null) destination.add(element) + return destination +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements that are not null to the given [destination] */ @@ -646,6 +701,16 @@ public inline fun > Iterable.filterNotTo(desti return destination } +/** + * Appends all elements not matching the given [predicate] to the given [destination] + */ +public inline fun > Sequence.filterNotTo(destination: C, predicate: (T) -> Boolean): C { + for (element in this) if (!predicate(element)) destination.add(element) + return destination +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements not matching the given [predicate] to the given [destination] */ @@ -742,6 +807,16 @@ public inline fun > Iterable.filterTo(destinat return destination } +/** + * Appends all elements matching the given [predicate] into the given [destination] + */ +public inline fun > Sequence.filterTo(destination: C, predicate: (T) -> Boolean): C { + for (element in this) if (predicate(element)) destination.add(element) + return destination +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements matching the given [predicate] into the given [destination] */ @@ -1046,6 +1121,15 @@ public fun Iterable.take(n: Int): List { return list } +/** + * Returns a sequence containing first *n* elements + */ +public fun Sequence.take(n: Int): Sequence { + return TakeSequence(this, n) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing first *n* elements */ @@ -1190,6 +1274,15 @@ public inline fun Iterable.takeWhile(predicate: (T) -> Boolean): List return list } +/** + * Returns a sequence containing first elements satisfying the given [predicate] + */ +public fun Sequence.takeWhile(predicate: (T) -> Boolean): Sequence { + return TakeWhileSequence(this, predicate) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing first elements satisfying the given [predicate] */ diff --git a/libraries/stdlib/src/generated/_Generators.kt b/libraries/stdlib/src/generated/_Generators.kt index 27354864a20..b71184cb2ea 100644 --- a/libraries/stdlib/src/generated/_Generators.kt +++ b/libraries/stdlib/src/generated/_Generators.kt @@ -270,7 +270,16 @@ public inline fun Iterable.merge(other: Iterable, 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 Sequence.merge(sequence: Sequence, transform: (T, R) -> V): Sequence { + return MergingSequence(this, sequence, transform) +} + + +deprecated("Migrate to using Sequence 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 Stream.merge(stream: Stream, transform: (T, R) -> V): Stream { return MergingStream(this, stream, transform) @@ -456,6 +465,26 @@ public inline fun Iterable.partition(predicate: (T) -> Boolean): Pair Sequence.partition(predicate: (T) -> Boolean): Pair, List> { + val first = ArrayList() + val second = ArrayList() + for (element in this) { + if (predicate(element)) { + first.add(element) + } else { + second.add(element) + } + } + return Pair(first, second) +} + + +deprecated("Migrate to using Sequence 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 Iterable.plus(collection: Iterable): List { } /** - * 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 Sequence.plus(collection: Iterable): Sequence { + return MultiSequence(sequenceOf(this, collection.sequence())) +} + + +deprecated("Migrate to using Sequence and respective functions") +/** + * Returns a stream containing all elements of original stream and then all elements of the given [collection] */ public fun Stream.plus(collection: Iterable): Stream { return Multistream(streamOf(this, collection.stream())) @@ -769,6 +807,15 @@ public fun Iterable.plus(element: T): List { return answer } +/** + * Returns a sequence containing all elements of original sequence and then the given element + */ +public fun Sequence.plus(element: T): Sequence { + return MultiSequence(sequenceOf(this, sequenceOf(element))) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements of original stream and then the given element */ @@ -777,7 +824,16 @@ public fun Stream.plus(element: T): Stream { } /** - * 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 Sequence.plus(sequence: Sequence): Sequence { + return MultiSequence(sequenceOf(this, sequence)) +} + + +deprecated("Migrate to using Sequence and respective functions") +/** + * Returns a stream containing all elements of original stream and then all elements of the given [stream] */ public fun Stream.plus(stream: Stream): Stream { return Multistream(streamOf(this, stream)) @@ -937,7 +993,18 @@ public fun String.zip(other: String): List> { } /** - * 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 Sequence.zip(sequence: Sequence): Sequence> { + return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 } +} + + +deprecated("Migrate to using Sequence 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 Stream.zip(stream: Stream): Stream> { return MergingStream(this, stream) { (t1, t2) -> t1 to t2 } diff --git a/libraries/stdlib/src/generated/_Guards.kt b/libraries/stdlib/src/generated/_Guards.kt index b48df152ac0..27bf0fd24e6 100644 --- a/libraries/stdlib/src/generated/_Guards.kt +++ b/libraries/stdlib/src/generated/_Guards.kt @@ -45,6 +45,20 @@ public fun List.requireNoNulls(): List { return this as List } +/** + * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements + */ +public fun Sequence.requireNoNulls(): Sequence { + return FilteringSequence(this) { + if (it == null) { + throw IllegalArgumentException("null element found in $this") + } + true + } as Sequence +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns an original collection containing all the non-*null* elements, throwing an [[IllegalArgumentException]] if there are any null elements */ diff --git a/libraries/stdlib/src/generated/_Mapping.kt b/libraries/stdlib/src/generated/_Mapping.kt index 06841c041ac..f4710afc6af 100644 --- a/libraries/stdlib/src/generated/_Mapping.kt +++ b/libraries/stdlib/src/generated/_Mapping.kt @@ -94,7 +94,16 @@ public inline fun String.flatMap(transform: (Char) -> Iterable): List } /** - * 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 Sequence.flatMap(transform: (T) -> Sequence): Sequence { + return FlatteningSequence(this, transform) +} + + +deprecated("Migrate to using Sequence 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 Stream.flatMap(transform: (T) -> Stream): Stream { return FlatteningStream(this, transform) @@ -232,6 +241,19 @@ public inline fun > 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 > Sequence.flatMapTo(destination: C, transform: (T) -> Sequence): C { + for (element in this) { + val list = transform(element) + destination.addAll(list) + } + return destination +} + + +deprecated("Migrate to using Sequence 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 Iterable.groupBy(toKey: (T) -> K): Map> { return groupByTo(LinkedHashMap>(), toKey) } +/** + * Returns a map of the elements in original collection grouped by the result of given *toKey* function + */ +public inline fun Sequence.groupBy(toKey: (T) -> K): Map> { + return groupByTo(LinkedHashMap>(), toKey) +} + + +deprecated("Migrate to using Sequence 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 Iterable.groupByTo(map: MutableMap return map } +/** + * Appends elements from original collection grouped by the result of given *toKey* function to the given *map* + */ +public inline fun Sequence.groupByTo(map: MutableMap>, toKey: (T) -> K): Map> { + for (element in this) { + val key = toKey(element) + val list = map.getOrPut(key) { ArrayList() } + list.add(element) + } + return map +} + + +deprecated("Migrate to using Sequence 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 Map.map(transform: (Map.Entry) -> R): Li return mapTo(ArrayList(), transform) } +/** + * Returns a sequence containing the results of applying the given *transform* function to each element of the original sequence + */ +public fun Sequence.map(transform: (T) -> R): Sequence { + return TransformingSequence(this, transform) +} + + +deprecated("Migrate to using Sequence 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 Iterable.mapIndexed(transform: (Int, T) -> R): List< return mapIndexedTo(ArrayList(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 Sequence.mapIndexed(transform: (Int, T) -> R): Sequence { + return TransformingIndexedSequence(this, transform) +} + + +deprecated("Migrate to using Sequence 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 > Map.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 > Sequence.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 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 Iterable.mapNotNull(transform: (T) -> R): Lis return mapNotNullTo(ArrayList(), transform) } +/** + * Returns a sequence containing the results of applying the given *transform* function to each non-null element of the original sequence + */ +public fun Sequence.mapNotNull(transform: (T) -> R): Sequence { + return TransformingSequence(FilteringSequence(this, false, { it == null }) as Sequence, transform) +} + + +deprecated("Migrate to using Sequence 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 > Iterable.mapNotN return destination } +/** + * Appends transformed non-null elements of original collection using the given *transform* function + * to the given *destination* + */ +public inline fun > Sequence.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 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 > Map.mapTo(destina return destination } +/** + * Appends transformed elements of the original collection using the given *transform* function + * to the given *destination* + */ +public inline fun > Sequence.mapTo(destination: C, transform: (T) -> R): C { + for (item in this) + destination.add(transform(item)) + return destination +} + + +deprecated("Migrate to using Sequence 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 Iterable.withIndex(): Iterable> { return IndexingIterable { iterator() } } +/** + * Returns a sequence of [IndexedValue] for each element of the original sequence + */ +public fun Sequence.withIndex(): Sequence> { + return IndexingSequence(this) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream of [IndexedValue] for each element of the original stream */ @@ -1153,6 +1274,17 @@ public fun Iterable.withIndices(): List> { return mapTo(ArrayList>(), { index++ to it }) } +/** + * Returns a sequence containing pairs of each element of the original collection and their index + */ +deprecated("Use withIndex() instead.") +public fun Sequence.withIndices(): Sequence> { + var index = 0 + return TransformingSequence(this, { index++ to it }) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing pairs of each element of the original collection and their index */ diff --git a/libraries/stdlib/src/generated/_Numeric.kt b/libraries/stdlib/src/generated/_Numeric.kt index 2351a9b35e8..e9040051864 100644 --- a/libraries/stdlib/src/generated/_Numeric.kt +++ b/libraries/stdlib/src/generated/_Numeric.kt @@ -21,6 +21,20 @@ public fun Iterable.sum(): Int { return sum } +/** + * Returns the sum of all elements in the collection + */ +public fun Sequence.sum(): Int { + val iterator = iterator() + var sum: Int = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the sum of all elements in the collection */ @@ -45,6 +59,20 @@ public fun Iterable.sum(): Long { return sum } +/** + * Returns the sum of all elements in the collection + */ +public fun Sequence.sum(): Long { + val iterator = iterator() + var sum: Long = 0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the sum of all elements in the collection */ @@ -69,6 +97,20 @@ public fun Iterable.sum(): Double { return sum } +/** + * Returns the sum of all elements in the collection + */ +public fun Sequence.sum(): Double { + val iterator = iterator() + var sum: Double = 0.0 + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the sum of all elements in the collection */ @@ -93,6 +135,20 @@ public fun Iterable.sum(): Float { return sum } +/** + * Returns the sum of all elements in the collection + */ +public fun Sequence.sum(): Float { + val iterator = iterator() + var sum: Float = 0.0f + while (iterator.hasNext()) { + sum += iterator.next() + } + return sum +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns the sum of all elements in the collection */ diff --git a/libraries/stdlib/src/generated/_Ordering.kt b/libraries/stdlib/src/generated/_Ordering.kt index b695fcd0675..fbcb9fdff12 100644 --- a/libraries/stdlib/src/generated/_Ordering.kt +++ b/libraries/stdlib/src/generated/_Ordering.kt @@ -272,6 +272,17 @@ public fun > Iterable.toSortedList(): List { return sortedList } +/** + * Returns a sorted list of all elements + */ +public fun > Sequence.toSortedList(): List { + val sortedList = toArrayList() + java.util.Collections.sort(sortedList) + return sortedList +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a sorted list of all elements */ @@ -381,6 +392,18 @@ public fun > Iterable.toSortedListBy(order: (T) -> V): L return sortedList } +/** + * Returns a sorted list of all elements, ordered by results of specified *order* function. + */ +public fun > Sequence.toSortedListBy(order: (T) -> V): List { + val sortedList = toArrayList() + val sortBy: Comparator = compareBy(order) + java.util.Collections.sort(sortedList, sortBy) + return sortedList +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a sorted list of all elements, ordered by results of specified *order* function. */ diff --git a/libraries/stdlib/src/generated/_Sequences.kt b/libraries/stdlib/src/generated/_Sequences.kt new file mode 100644 index 00000000000..770c226a648 --- /dev/null +++ b/libraries/stdlib/src/generated/_Sequences.kt @@ -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 Array.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun BooleanArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun ByteArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun CharArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun DoubleArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun FloatArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun IntArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun LongArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun ShortArray.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun Iterable.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun Map.sequence(): Sequence> { + return object : Sequence> { + override fun iterator(): Iterator> { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +public fun Sequence.sequence(): Sequence { + return this +} + + +deprecated("Migrate to using Sequence and respective functions") +/** + * Returns a stream from the given collection + */ +public fun Stream.stream(): Stream { + return this +} + +/** + * Returns a sequence from the given collection + */ +public fun String.sequence(): Sequence { + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun Array.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun BooleanArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun ByteArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun CharArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun DoubleArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun FloatArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun IntArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun LongArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun ShortArray.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun Iterable.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun Map.stream(): Stream> { + val sequence = sequence() + return object : Stream> { + override fun iterator(): Iterator> { + return sequence.iterator() + } + } +} + +/** + * Returns a sequence from the given collection + */ +deprecated("Use sequence() instead") +public fun String.stream(): Stream { + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } +} + diff --git a/libraries/stdlib/src/generated/_Snapshots.kt b/libraries/stdlib/src/generated/_Snapshots.kt index e285b1d24bf..b762c2a8008 100644 --- a/libraries/stdlib/src/generated/_Snapshots.kt +++ b/libraries/stdlib/src/generated/_Snapshots.kt @@ -97,6 +97,15 @@ public fun Iterable.toArrayList(): ArrayList { return toCollection(ArrayList(collectionSizeOrDefault(10))) } +/** + * Returns an ArrayList of all elements + */ +public fun Sequence.toArrayList(): ArrayList { + return toCollection(ArrayList()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns an ArrayList of all elements */ @@ -211,6 +220,18 @@ public fun > Iterable.toCollection(collection: return collection } +/** + * Appends all elements to the given *collection* + */ +public fun > Sequence.toCollection(collection: C): C { + for (item in this) { + collection.add(item) + } + return collection +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements to the given *collection* */ @@ -301,6 +322,15 @@ public fun Iterable.toHashSet(): HashSet { return toCollection(HashSet()) } +/** + * Returns a HashSet of all elements + */ +public fun Sequence.toHashSet(): HashSet { + return toCollection(HashSet()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a HashSet of all elements */ @@ -385,6 +415,15 @@ public fun Iterable.toLinkedList(): LinkedList { return toCollection(LinkedList()) } +/** + * Returns a LinkedList containing all elements + */ +public fun Sequence.toLinkedList(): LinkedList { + return toCollection(LinkedList()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a LinkedList containing all elements */ @@ -497,6 +536,15 @@ public fun Iterable.toList(): List { return toCollection(ArrayList(collectionSizeOrDefault(10))) } +/** + * Returns a List containing all elements + */ +public fun Sequence.toList(): List { + return toCollection(ArrayList()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a List containing all elements */ @@ -621,6 +669,19 @@ public inline fun Iterable.toMap(selector: (T) -> K): Map { return result } +/** + * Returns Map containing all the values from the given collection indexed by *selector* + */ +public inline fun Sequence.toMap(selector: (T) -> K): Map { + val result = LinkedHashMap() + for (element in this) { + result.put(selector(element), element) + } + return result +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns Map containing all the values from the given collection indexed by *selector* */ @@ -713,6 +774,15 @@ public fun Iterable.toSet(): Set { return toCollection(LinkedHashSet()) } +/** + * Returns a Set of all elements + */ +public fun Sequence.toSet(): Set { + return toCollection(LinkedHashSet()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a Set of all elements */ @@ -797,6 +867,15 @@ public fun Iterable.toSortedSet(): SortedSet { return toCollection(TreeSet()) } +/** + * Returns a SortedSet of all elements + */ +public fun Sequence.toSortedSet(): SortedSet { + return toCollection(TreeSet()) +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a SortedSet of all elements */ diff --git a/libraries/stdlib/src/generated/_SpecialJVM.kt b/libraries/stdlib/src/generated/_SpecialJVM.kt index 6700360e8fd..9582f1047b1 100644 --- a/libraries/stdlib/src/generated/_SpecialJVM.kt +++ b/libraries/stdlib/src/generated/_SpecialJVM.kt @@ -467,6 +467,15 @@ public inline fun Iterable<*>.filterIsInstance(): List { return filterIsInstanceTo(ArrayList()) } +/** + * Returns a sequence containing all elements that are instances of specified type parameter R + */ +public inline fun Sequence<*>.filterIsInstance(): Sequence { + return FilteringSequence(this, true, { it is R }) as Sequence +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements that are instances of specified type parameter R */ @@ -488,6 +497,15 @@ public fun Iterable<*>.filterIsInstance(klass: Class): List { return filterIsInstanceTo(ArrayList(), klass) } +/** + * Returns a sequence containing all elements that are instances of specified class + */ +public fun Sequence<*>.filterIsInstance(klass: Class): Sequence { + return FilteringSequence(this, true, { klass.isInstance(it) }) as Sequence +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Returns a stream containing all elements that are instances of specified class */ @@ -511,6 +529,16 @@ public inline fun > Iterable<*>.filterIsI return destination } +/** + * Appends all elements that are instances of specified type parameter R to the given *destination* + */ +public inline fun > Sequence<*>.filterIsInstanceTo(destination: C): C { + for (element in this) if (element is R) destination.add(element) + return destination +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements that are instances of specified type parameter R to the given *destination* */ @@ -535,6 +563,16 @@ public fun , R> Iterable<*>.filterIsInstanceTo(desti return destination } +/** + * Appends all elements that are instances of specified class to the given *destination* + */ +public fun , R> Sequence<*>.filterIsInstanceTo(destination: C, klass: Class): C { + for (element in this) if (klass.isInstance(element)) destination.add(element as R) + return destination +} + + +deprecated("Migrate to using Sequence and respective functions") /** * Appends all elements that are instances of specified class to the given *destination* */ diff --git a/libraries/stdlib/src/generated/_Streams.kt b/libraries/stdlib/src/generated/_Streams.kt deleted file mode 100644 index 87955f78af6..00000000000 --- a/libraries/stdlib/src/generated/_Streams.kt +++ /dev/null @@ -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 Array.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun BooleanArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun ByteArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun CharArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun DoubleArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun FloatArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun IntArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun LongArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun ShortArray.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun Iterable.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun Map.stream(): Stream> { - return object : Stream> { - override fun iterator(): Iterator> { - return this@stream.iterator() - } - } -} - -/** - * Returns a stream from the given collection - */ -public fun Stream.stream(): Stream { - return this -} - -/** - * Returns a stream from the given collection - */ -public fun String.stream(): Stream { - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } -} - diff --git a/libraries/stdlib/src/generated/_Strings.kt b/libraries/stdlib/src/generated/_Strings.kt index 42153975b4f..3e1a9154c80 100644 --- a/libraries/stdlib/src/generated/_Strings.kt +++ b/libraries/stdlib/src/generated/_Strings.kt @@ -209,6 +209,28 @@ public fun Iterable.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 Sequence.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 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 Iterable.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 Sequence.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 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] diff --git a/libraries/stdlib/src/kotlin/collections/MutableCollections.kt b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt index f34c31ee605..0833c2a8718 100644 --- a/libraries/stdlib/src/kotlin/collections/MutableCollections.kt +++ b/libraries/stdlib/src/kotlin/collections/MutableCollections.kt @@ -11,8 +11,16 @@ public fun MutableCollection.addAll(iterable: Iterable) { } /** - * Adds all elements of the given [stream] to this [MutableCollection]. + * Adds all elements of the given [sequence] to this [MutableCollection]. */ +public fun MutableCollection.addAll(sequence: Sequence) { + for (item in sequence) add(item) +} + +/** + * Adds all elements of the given [sequence] to this [MutableCollection]. + */ +deprecated("Use Sequence instead of Stream") public fun MutableCollection.addAll(stream: Stream) { for (item in stream) add(item) } @@ -34,9 +42,17 @@ public fun MutableCollection.removeAll(iterable: Iterable) { } } +/** + * Removes all elements of the given [sequence] from this [MutableCollection]. + */ +public fun MutableCollection.removeAll(sequence: Sequence) { + for (item in sequence) remove(item) +} + /** * Removes all elements of the given [stream] from this [MutableCollection]. */ +deprecated("Use Sequence instead of Stream") public fun MutableCollection.removeAll(stream: Stream) { for (item in stream) remove(item) } diff --git a/libraries/stdlib/src/kotlin/collections/Operations.kt b/libraries/stdlib/src/kotlin/collections/Operations.kt index 676e092b4e5..58c232345d2 100644 --- a/libraries/stdlib/src/kotlin/collections/Operations.kt +++ b/libraries/stdlib/src/kotlin/collections/Operations.kt @@ -15,8 +15,16 @@ public fun Iterable>.flatten(): List { } /** - * 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 Sequence>.flatten(): Sequence { + return FlatteningSequence(this, { it }) +} + +/** + * Returns a sequence of all elements from all sequences in this sequence. + */ +deprecated("Use Sequence instead of Stream") public fun Stream>.flatten(): Stream { return FlatteningStream(this, { it }) } diff --git a/libraries/stdlib/src/kotlin/collections/Stream.kt b/libraries/stdlib/src/kotlin/collections/Sequence.kt similarity index 55% rename from libraries/stdlib/src/kotlin/collections/Stream.kt rename to libraries/stdlib/src/kotlin/collections/Sequence.kt index 3273c154ef2..b924f0dfce8 100644 --- a/libraries/stdlib/src/kotlin/collections/Stream.kt +++ b/libraries/stdlib/src/kotlin/collections/Sequence.kt @@ -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 instead.") public trait Stream { /** * Returns an iterator that returns the values from the sequence. @@ -16,31 +11,55 @@ public trait Stream { } /** - * 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 : Stream + +public fun Stream.toSequence(): Sequence = object : Sequence { + override fun iterator(): Iterator = this@toSequence.iterator() +} + +deprecated("Use sequenceOf() instead") public fun streamOf(vararg elements: T): Stream = elements.stream() -/** - * Creates a stream that returns all values in the specified [progression]. - */ +deprecated("Use sequenceOf() instead") public fun streamOf(progression: Progression): Stream = object : Stream { override fun iterator(): Iterator = 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 sequenceOf(vararg elements: T): Sequence = elements.sequence() + +/** + * Creates a sequence that returns all values in the specified [progression]. + */ +public fun sequenceOf(progression: Progression): Sequence = object : Sequence { + override fun iterator(): Iterator = progression.iterator() +} + +deprecated("Use FilteringSequence instead") +public class FilteringStream(stream: Stream, sendWhen: Boolean = true, predicate: (T) -> Boolean) +: Stream by FilteringSequence(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(private val stream: Stream, - private val sendWhen: Boolean = true, - private val predicate: (T) -> Boolean - ) : Stream { +public class FilteringSequence(private val sequence: Sequence, + private val sendWhen: Boolean = true, + private val predicate: (T) -> Boolean + ) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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(private val stream: Stream, } } +deprecated("Use TransformingSequence instead") +public class TransformingStream(stream: Stream, transformer: (T) -> R) +: Stream by TransformingSequence(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(private val stream: Stream, private val transformer: (T) -> R) : Stream { +public class TransformingSequence(private val sequence: Sequence, private val transformer: (T) -> R) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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 instead") +public class TransformingIndexedStream(stream: Stream, transformer: (Int, T) -> R) +: Stream by TransformingIndexedSequence(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(private val stream: Stream, private val transformer: (Int, T) -> R) : Stream { +public class TransformingIndexedSequence(private val sequence: Sequence, private val transformer: (Int, T) -> R) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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 instead") +public class IndexingStream(stream: Stream) +: Stream> 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(private val stream: Stream) : Stream> { +public class IndexingSequence(private val sequence: Sequence) : Sequence> { override fun iterator(): Iterator> = object : Iterator> { - val iterator = stream.iterator() + val iterator = sequence.iterator() var index = 0 override fun next(): IndexedValue { return IndexedValue(index++, iterator.next()) @@ -127,32 +160,41 @@ public class IndexingStream(private val stream: Stream) : Stream instead") +public class MergingStream(stream1: Stream, stream2: Stream, transform: (T1, T2) -> V) +: Stream 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(private val stream1: Stream, - private val stream2: Stream, - private val transform: (T1, T2) -> V - ) : Stream { +public class MergingSequence(private val sequence1: Sequence, + private val sequence2: Sequence, + private val transform: (T1, T2) -> V + ) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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(private val stream: Stream, - private val transformer: (T) -> Stream - ) : Stream { +deprecated("Use FlatteningSequence instead") +public class FlatteningStream(stream: Stream, transformer: (T) -> Stream) +: Stream by FlatteningSequence(stream.toSequence(), { transformer(it).toSequence() }) + +public class FlatteningSequence(private val sequence: Sequence, + private val transformer: (T) -> Sequence + ) : Sequence { override fun iterator(): Iterator = object : Iterator { - val iterator = stream.iterator() + val iterator = sequence.iterator() var itemIterator: Iterator? = null override fun next(): R { @@ -186,9 +228,13 @@ public class FlatteningStream(private val stream: Stream, } } -public class Multistream(private val stream: Stream>) : Stream { +deprecated("Use MultiSequence instead") +public class Multistream(stream: Stream>) +: Stream by FlatteningSequence(stream.toSequence(), { it.toSequence() }) + +public class MultiSequence(private val sequence: Sequence>) : Sequence { override fun iterator(): Iterator = object : Iterator { - val iterator = stream.iterator() + val iterator = sequence.iterator() var itemIterator: Iterator? = null override fun next(): T { @@ -222,13 +268,17 @@ public class Multistream(private val stream: Stream>) : Stream { } } +deprecated("Use TakeSequence instead") +public class TakeStream(stream: Stream, count: Int) +: Stream 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(private val stream: Stream, - private val count: Int - ) : Stream { +public class TakeSequence(private val sequence: Sequence, + private val count: Int + ) : Sequence { { if (count < 0) throw IllegalArgumentException("count should be non-negative, but is $count") @@ -236,7 +286,7 @@ public class TakeStream(private val stream: Stream, override fun iterator(): Iterator = object : Iterator { 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(private val stream: Stream, } } +deprecated("Use TakeWhileSequence instead") +public class TakeWhileStream(stream: Stream, predicate: (T) -> Boolean) : Stream by TakeWhileSequence(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(private val stream: Stream, - private val predicate: (T) -> Boolean - ) : Stream { +public class TakeWhileSequence(private val sequence: Sequence, + private val predicate: (T) -> Boolean + ) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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(private val stream: Stream, } } +deprecated("Use DropSequence instead") +public class DropStream(stream: Stream, count: Int) +: Stream by DropSequence(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(private val stream: Stream, - private val count: Int - ) : Stream { +public class DropSequence(private val sequence: Sequence, + private val count: Int + ) : Sequence { { if (count < 0) throw IllegalArgumentException("count should be non-negative, but is $count") } override fun iterator(): Iterator = object : Iterator { - 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(private val stream: Stream, } } +deprecated("Use DropWhileSequence instead") +public class DropWhileStream(stream: Stream, predicate: (T) -> Boolean) : Stream by DropWhileSequence(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(private val stream: Stream, - private val predicate: (T) -> Boolean - ) : Stream { +public class DropWhileSequence(private val sequence: Sequence, + private val predicate: (T) -> Boolean + ) : Sequence { override fun iterator(): Iterator = object : Iterator { - 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(private val stream: Stream, } /** - * 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(private val producer: () -> T?) : Stream { +public class FunctionSequence(private val producer: () -> T?) : Sequence { override fun iterator(): Iterator = object : Iterator { var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue var nextItem: T? = null @@ -419,16 +479,21 @@ public class FunctionStream(private val producer: () -> T?) : Stream } /** - * 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 stream(nextFunction: () -> T?): Stream { - return FunctionStream(nextFunction) +public fun sequence(nextFunction: () -> T?): Sequence { + return FunctionSequence(nextFunction) } +deprecated("Use sequence() instead") +public fun stream(nextFunction: () -> T?): Sequence = 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 stream(initialValue: T, nextFunction: (T) -> T?): Stream = - stream(nextFunction.toGenerator(initialValue)) +public /*inline*/ fun sequence(initialValue: T, nextFunction: (T) -> T?): Sequence = + sequence(nextFunction.toGenerator(initialValue)) +deprecated("Use sequence() instead") +public /*inline*/ fun stream(initialValue: T, nextFunction: (T) -> T?): Sequence = sequence(initialValue, nextFunction) diff --git a/libraries/stdlib/src/kotlin/deprecated/Iterators.kt b/libraries/stdlib/src/kotlin/deprecated/Iterators.kt index c13f229124e..00d9bf02a4a 100644 --- a/libraries/stdlib/src/kotlin/deprecated/Iterators.kt +++ b/libraries/stdlib/src/kotlin/deprecated/Iterators.kt @@ -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 iterate(nextFunction: () -> T?) : Iterator { return FunctionIterator(nextFunction) } @@ -16,20 +16,20 @@ public fun iterate(nextFunction: () -> T?) : Iterator { * 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 iterate(initialValue: T, nextFunction: (T) -> T?): Iterator = iterate(nextFunction.toGenerator(initialValue)) /** * Returns an iterator whose values are pairs composed of values produced by given pair of iterators */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.zip(iterator: Iterator): Iterator> = PairIterator(this, iterator) /** * Returns an iterator shifted to right by the given number of elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.skip(n: Int): Iterator = SkippingIterator(this, n) deprecated("Use FilteringStream instead") diff --git a/libraries/stdlib/src/kotlin/deprecated/Strings.kt b/libraries/stdlib/src/kotlin/deprecated/Strings.kt index 543d882ade2..28cbd91caa8 100644 --- a/libraries/stdlib/src/kotlin/deprecated/Strings.kt +++ b/libraries/stdlib/src/kotlin/deprecated/Strings.kt @@ -52,7 +52,7 @@ public fun Iterable.makeString(separator: String = ", ", prefix: String = } deprecated("Use joinToString() instead") -public fun Stream.makeString(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { +public fun Sequence.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 Iterable.appendString(buffer: Appendable, separator: String = } deprecated("Use joinTo() instead") -public fun Stream.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { +public fun Sequence.appendString(buffer: Appendable, separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): Unit { joinTo(buffer, separator, prefix, postfix, limit, truncated) } diff --git a/libraries/stdlib/src/kotlin/deprecated/_Iterators.kt b/libraries/stdlib/src/kotlin/deprecated/_Iterators.kt index 4832625ef54..b320bcffb22 100644 --- a/libraries/stdlib/src/kotlin/deprecated/_Iterators.kt +++ b/libraries/stdlib/src/kotlin/deprecated/_Iterators.kt @@ -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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.all(predicate: (T) -> Boolean) : Boolean { for (element in this) if (!predicate(element)) return false return true @@ -20,7 +20,7 @@ public inline fun Iterator.all(predicate: (T) -> Boolean) : Boolean { /** * Returns *true* if any elements match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.any(predicate: (T) -> Boolean) : Boolean { for (element in this) if (predicate(element)) return true return false @@ -31,7 +31,7 @@ public inline fun Iterator.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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.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 Iterator.appendString(buffer: Appendable, separator: String = /** * Returns the number of elements which match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.count(predicate: (T) -> Boolean) : Int { var count = 0 for (element in this) if (predicate(element)) count++ @@ -59,7 +59,7 @@ public inline fun Iterator.count(predicate: (T) -> Boolean) : Int { /** * Returns a list containing everything but the first *n* elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.drop(n: Int) : List { return dropWhile(countTo(n)) } @@ -67,7 +67,7 @@ public fun Iterator.drop(n: Int) : List { /** * Returns a list containing the everything but the first elements that satisfy the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.dropWhile(predicate: (T) -> Boolean) : List { return dropWhileTo(ArrayList(), predicate) } @@ -75,7 +75,7 @@ public inline fun Iterator.dropWhile(predicate: (T) -> Boolean) : List /** * Returns a list containing the everything but the first elements that satisfy the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.dropWhileTo(result: L, predicate: (T) -> Boolean) : L { var start = true for (element in this) { @@ -92,7 +92,7 @@ public inline fun > Iterator.dropWhileTo(result: L, p /** * Returns an iterator over elements which match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.filter(predicate: (T) -> Boolean) : Iterator { return FilterIterator(this, predicate) } @@ -100,7 +100,7 @@ public fun Iterator.filter(predicate: (T) -> Boolean) : Iterator { /** * Returns an iterator over elements which don't match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.filterNot(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) predicate: (T) -> Boolean) : Iterator { return filter {!predicate(it)} } @@ -108,7 +108,7 @@ public inline fun Iterator.filterNot(inlineOptions(InlineOption.ONLY_LOCA /** * Returns an iterator over non-*null* elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.filterNotNull() : Iterator { return FilterNotNullIterator(this) } @@ -116,7 +116,7 @@ public fun Iterator.filterNotNull() : Iterator { /** * Filters all non-*null* elements into the given list */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun > Iterator.filterNotNullTo(result: C) : C { for (element in this) if (element != null) result.add(element) return result @@ -125,7 +125,7 @@ public fun > Iterator.filterNotNullTo(resu /** * Returns a list containing all elements which do not match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.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 > Iterator.filterNotTo(result /** * Filters all elements which match the given predicate into the given list */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.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 > Iterator.filterTo(result: C /** * Returns the first element which matches the given *predicate* or *null* if none matched */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.find(predicate: (T) -> Boolean) : T? { for (element in this) if (predicate(element)) return element return null @@ -152,7 +152,7 @@ public inline fun Iterator.find(predicate: (T) -> Boolean) : T? { /** * Returns an iterator over the concatenated results of transforming each element to one or more values */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.flatMap(transform: (T) -> Iterator) : Iterator { return FlatMapIterator(this, transform) } @@ -160,7 +160,7 @@ public fun Iterator.flatMap(transform: (T) -> Iterator) : Iterator< /** * Returns the result of transforming each element to one or more values which are concatenated together into a single collection */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.flatMapTo(result: C, transform: (T) -> Iterable) : C { for (element in this) { val list = transform(element) @@ -172,7 +172,7 @@ public inline fun > Iterator.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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.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 Iterator.fold(initial: R, operation: (R, T) -> R) : /** * Performs the given *operation* on each element */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.forEach(operation: (T) -> Unit) : Unit { for (element in this) operation(element) } @@ -190,12 +190,12 @@ public inline fun Iterator.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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.groupBy(toKey: (T) -> K) : Map> { return groupByTo(HashMap>(), toKey) } -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.groupByTo(result: MutableMap>, toKey: (T) -> K) : Map> { for (element in this) { val key = toKey(element) @@ -210,7 +210,7 @@ public inline fun Iterator.groupByTo(result: MutableMap with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.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 Iterator.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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.map(transform : (T) -> R) : Iterator { return MapIterator(this, transform) } @@ -231,7 +231,7 @@ public fun Iterator.map(transform : (T) -> R) : Iterator { * Transforms each element of this collection with the given *transform* function and * adds each return value to the given *results* collection */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.mapTo(result: C, transform : (T) -> R) : C { for (item in this) result.add(transform(item)) @@ -241,7 +241,7 @@ public inline fun > Iterator.mapTo(result: C /** * Returns the largest element or null if there are no elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun > Iterator.max() : T? { if (!hasNext()) return null @@ -256,7 +256,7 @@ public fun > Iterator.max() : T? { /** * Returns the first element yielding the largest value of the given function or null if there are no elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun , T: Any> Iterator.maxBy(f: (T) -> R) : T? { if (!hasNext()) return null @@ -276,7 +276,7 @@ public inline fun , T: Any> Iterator.maxBy(f: (T) -> R) : T? /** * Returns the smallest element or null if there are no elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun > Iterator.min() : T? { if (!hasNext()) return null @@ -291,7 +291,7 @@ public fun > Iterator.min() : T? { /** * Returns the first element yielding the smallest value of the given function or null if there are no elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun , T: Any> Iterator.minBy(f: (T) -> R) : T? { if (!hasNext()) return null @@ -311,7 +311,7 @@ public inline fun , T: Any> Iterator.minBy(f: (T) -> R) : T? /** * Partitions this collection into a pair of collections */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.partition(predicate: (T) -> Boolean) : Pair, List> { val first = ArrayList() val second = ArrayList() @@ -328,7 +328,7 @@ public inline fun Iterator.partition(predicate: (T) -> Boolean) : Pair
  • with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.plus(collection: Iterable) : Iterator { return plus(collection.iterator()) } @@ -336,7 +336,7 @@ public fun Iterator.plus(collection: Iterable) : Iterator { /** * Creates an [[Iterator]] which iterates over this iterator then the given element at the end */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.plus(element: T) : Iterator { return CompositeIterator(this, SingleIterator(element)) } @@ -344,7 +344,7 @@ public fun Iterator.plus(element: T) : Iterator { /** * Creates an [[Iterator]] which iterates over this iterator then the following iterator */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.plus(iterator: Iterator) : Iterator { return CompositeIterator(this, iterator) } @@ -353,7 +353,7 @@ public fun Iterator.plus(iterator: Iterator) : Iterator { * 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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun Iterator.reduce(operation: (T, T) -> T) : T { val iterator = this.iterator() if (!iterator.hasNext()) { @@ -371,7 +371,7 @@ public inline fun Iterator.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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.requireNoNulls() : Iterator { return map{ if (it == null) throw IllegalArgumentException("null element in iterator $this") else it @@ -381,7 +381,7 @@ public fun Iterator.requireNoNulls() : Iterator { /** * Reverses the order the elements into a list */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.reverse() : List { val list = toCollection(ArrayList()) Collections.reverse(list) @@ -392,7 +392,7 @@ public fun Iterator.reverse() : List { * 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 with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.sortBy(inlineOptions(InlineOption.ONLY_LOCAL_RETURN) f: (T) -> R) : List { val sortedList = toCollection(ArrayList()) val sortBy: Comparator = comparator {(x: T, y: T) -> @@ -407,7 +407,7 @@ public inline fun > Iterator.sortBy(inlineOptions(InlineO /** * Returns an iterator restricted to the first *n* elements */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.take(n: Int) : Iterator { var count = n return takeWhile{ --count >= 0 } @@ -416,7 +416,7 @@ public fun Iterator.take(n: Int) : Iterator { /** * Returns an iterator restricted to the first elements that match the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.takeWhile(predicate: (T) -> Boolean) : Iterator { return TakeWhileIterator(this, predicate) } @@ -424,7 +424,7 @@ public fun Iterator.takeWhile(predicate: (T) -> Boolean) : Iterator { /** * Returns a list containing the first elements that satisfy the given *predicate* */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public inline fun > Iterator.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 > Iterator.takeWhileTo(result /** * Copies all elements into the given collection */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun > Iterator.toCollection(result: C) : C { for (element in this) result.add(element) return result @@ -442,7 +442,7 @@ public fun > Iterator.toCollection(result: C) : /** * Copies all elements into a [[LinkedList]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toLinkedList() : LinkedList { return toCollection(LinkedList()) } @@ -450,7 +450,7 @@ public fun Iterator.toLinkedList() : LinkedList { /** * Copies all elements into a [[List]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toList() : List { return toCollection(ArrayList()) } @@ -458,7 +458,7 @@ public fun Iterator.toList() : List { /** * Copies all elements into a [[ArrayList]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toArrayList() : ArrayList { return toCollection(ArrayList()) } @@ -466,7 +466,7 @@ public fun Iterator.toArrayList() : ArrayList { /** * Copies all elements into a [[Set]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toSet() : Set { return toCollection(LinkedHashSet()) } @@ -474,7 +474,7 @@ public fun Iterator.toSet() : Set { /** * Copies all elements into a [[HashSet]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toHashSet() : HashSet { return toCollection(HashSet()) } @@ -482,7 +482,7 @@ public fun Iterator.toHashSet() : HashSet { /** * Copies all elements into a [[SortedSet]] */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.toSortedSet() : SortedSet { return toCollection(TreeSet()) } @@ -490,7 +490,7 @@ public fun Iterator.toSortedSet() : SortedSet { /** * Returns an iterator of Pairs(index, data) */ -deprecated("Replace Iterator with Stream by using stream() function instead of iterator()") +deprecated("Replace Iterator with Sequence by using sequence() function instead of iterator()") public fun Iterator.withIndices() : Iterator> { return IndexIterator(iterator()) } diff --git a/libraries/stdlib/src/kotlin/io/ReadWrite.kt b/libraries/stdlib/src/kotlin/io/ReadWrite.kt index 3de5e5d4100..d441139b617 100644 --- a/libraries/stdlib/src/kotlin/io/ReadWrite.kt +++ b/libraries/stdlib/src/kotlin/io/ReadWrite.kt @@ -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 Reader.useLines(block: (Stream) -> T): T = +public inline fun Reader.useLines(block: (Sequence) -> T): T = this.buffered().use { block(it.lines()) } /** @@ -169,12 +169,12 @@ public inline fun Reader.useLines(block: (Stream) -> T): T = * * We suggest you try the method [useLines] instead which closes the stream when the processing is complete. */ -public fun BufferedReader.lines(): Stream = LinesStream(this) +public fun BufferedReader.lines(): Sequence = LinesStream(this) deprecated("Use lines() function which returns Stream") public fun BufferedReader.lineIterator(): Iterator = lines().iterator() -private class LinesStream(private val reader: BufferedReader) : Stream { +private class LinesStream(private val reader: BufferedReader) : Sequence { override fun iterator(): Iterator { return object : Iterator { private var nextValue: String? = null diff --git a/libraries/stdlib/src/kotlin/text/Strings.kt b/libraries/stdlib/src/kotlin/text/Strings.kt index 9ea5752f8e6..7bfa4ab5eeb 100644 --- a/libraries/stdlib/src/kotlin/text/Strings.kt +++ b/libraries/stdlib/src/kotlin/text/Strings.kt @@ -131,6 +131,11 @@ public fun Array.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.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 and respective functions") public fun Stream.join(separator: String = ", ", prefix: String = "", postfix: String = "", limit: Int = -1, truncated: String = "..."): String { return joinToString(separator, prefix, postfix, limit, truncated) } diff --git a/libraries/stdlib/test/collections/ArraysTest.kt b/libraries/stdlib/test/collections/ArraysTest.kt index bf4bd15ae2b..2a65363a044 100644 --- a/libraries/stdlib/test/collections/ArraysTest.kt +++ b/libraries/stdlib/test/collections/ArraysTest.kt @@ -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() { diff --git a/libraries/stdlib/test/collections/CollectionTest.kt b/libraries/stdlib/test/collections/CollectionTest.kt index e9eebb9319c..6c0b04cc79f 100644 --- a/libraries/stdlib/test/collections/CollectionTest.kt +++ b/libraries/stdlib/test/collections/CollectionTest.kt @@ -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().stream().min() }) - expect(2, { listOf(2, 3).stream().min() }) + expect(null, { listOf().sequence().min() }) + expect(2, { listOf(2, 3).sequence().min() }) } 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().stream().max() }) - expect(3, { listOf(2, 3).stream().max() }) + expect(null, { listOf().sequence().max() }) + expect(3, { listOf(2, 3).sequence().max() }) } 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().stream().minBy { it } }) - expect(3, { listOf(2, 3).stream().minBy { -it } }) + expect(null, { listOf().sequence().minBy { it } }) + expect(3, { listOf(2, 3).sequence().minBy { -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().stream().maxBy { it } }) - expect(2, { listOf(2, 3).stream().maxBy { -it } }) + expect(null, { listOf().sequence().maxBy { it } }) + expect(2, { listOf(2, 3).sequence().maxBy { -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 { 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 { c++; it * it } }) assertEquals(5, c) } @@ -435,7 +435,7 @@ class CollectionTest { expect(3.0) { listOf(1.0, 2.0).sum() } expect(3000000000000) { arrayListOf(1000000000000, 2000000000000).sum() } expect(3.0.toFloat()) { arrayListOf(1.0.toFloat(), 2.0.toFloat()).sum() } - expect(3.0.toFloat()) { streamOf(1.0.toFloat(), 2.0.toFloat()).sum() } + expect(3.0.toFloat()) { sequenceOf(1.0.toFloat(), 2.0.toFloat()).sum() } } test fun takeReturnsFirstNElements() { diff --git a/libraries/stdlib/test/collections/MapTest.kt b/libraries/stdlib/test/collections/MapTest.kt index 6dbe14f26bf..701fe1b7ad4 100644 --- a/libraries/stdlib/test/collections/MapTest.kt +++ b/libraries/stdlib/test/collections/MapTest.kt @@ -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) } diff --git a/libraries/stdlib/test/collections/MutableCollectionsTest.kt b/libraries/stdlib/test/collections/MutableCollectionsTest.kt index 1b2d0f02934..943ce27a075 100644 --- a/libraries/stdlib/test/collections/MutableCollectionsTest.kt +++ b/libraries/stdlib/test/collections/MutableCollectionsTest.kt @@ -21,7 +21,7 @@ class MutableCollectionTest { val list = listOf("foo", "bar") val collection = ArrayList() - collection.addAll(list.stream()) + collection.addAll(list.sequence()) assertEquals(list, collection) } diff --git a/libraries/stdlib/test/collections/SequenceJVMTest.kt b/libraries/stdlib/test/collections/SequenceJVMTest.kt new file mode 100644 index 00000000000..51cf0adf925 --- /dev/null +++ b/libraries/stdlib/test/collections/SequenceJVMTest.kt @@ -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 = listOf(1, 2, 3.toDouble(), "abc", "cde").sequence() + + val intValues: Sequence = src.filterIsInstance() + assertEquals(listOf(1, 2), intValues.toArrayList()) + + val doubleValues: Sequence = src.filterIsInstance() + assertEquals(listOf(3.0), doubleValues.toArrayList()) + + val stringValues: Sequence = src.filterIsInstance() + assertEquals(listOf("abc", "cde"), stringValues.toArrayList()) + + val anyValues: Sequence = src.filterIsInstance() + assertEquals(src.toList(), anyValues.toArrayList()) + + val charValues: Sequence = src.filterIsInstance() + assertEquals(0, charValues.toArrayList().size()) + } +} diff --git a/libraries/stdlib/test/collections/StreamTest.kt b/libraries/stdlib/test/collections/SequenceTest.kt similarity index 79% rename from libraries/stdlib/test/collections/StreamTest.kt rename to libraries/stdlib/test/collections/SequenceTest.kt index c1fcd6b8b68..b78e5c74b3d 100644 --- a/libraries/stdlib/test/collections/StreamTest.kt +++ b/libraries/stdlib/test/collections/SequenceTest.kt @@ -4,12 +4,12 @@ import org.junit.Test as test import kotlin.test.* import java.util.* -fun fibonacci(): Stream { +fun fibonacci(): Sequence { // 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 { } } -public class StreamTest { +public class SequenceTest { - test fun filterEmptyStream() { - val stream = streamOf() + test fun filterEmptySequence() { + val stream = sequenceOf() assertEquals(0, stream.filter { false }.count()) assertEquals(0, stream.filter { true }.count()) } test fun mapEmptyStream() { - val stream = streamOf() + val stream = sequenceOf() assertEquals(0, stream.map { false }.count()) assertEquals(0, stream.map { true }.count()) } test fun requireNoNulls() { - val stream = streamOf("foo", "bar") + val stream = sequenceOf("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 + foo is Sequence } } 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 > Stream.takeWhileTo(result: C, predicate: (T) -> Boolean): C { + private fun > Sequence.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() - 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().flatMap { streamOf(0..it) } + val result = sequenceOf().flatMap { sequenceOf(0..it) } assertTrue(result.none()) } test fun flatMapWithEmptyItems() { - val result = streamOf(1, 2, 4).flatMap { if (it == 2) streamOf() else streamOf(it - 1..it) } + val result = sequenceOf(1, 2, 4).flatMap { if (it == 2) sequenceOf() 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()) } diff --git a/libraries/stdlib/test/collections/StreamJVMTest.kt b/libraries/stdlib/test/collections/StreamJVMTest.kt deleted file mode 100644 index 4217e5a328f..00000000000 --- a/libraries/stdlib/test/collections/StreamJVMTest.kt +++ /dev/null @@ -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 = listOf(1, 2, 3.toDouble(), "abc", "cde").stream() - - val intValues: Stream = src.filterIsInstance() - assertEquals(listOf(1, 2), intValues.toArrayList()) - - val doubleValues: Stream = src.filterIsInstance() - assertEquals(listOf(3.0), doubleValues.toArrayList()) - - val stringValues: Stream = src.filterIsInstance() - assertEquals(listOf("abc", "cde"), stringValues.toArrayList()) - - val anyValues: Stream = src.filterIsInstance() - assertEquals(src.toList(), anyValues.toArrayList()) - - val charValues: Stream = src.filterIsInstance() - assertEquals(0, charValues.toArrayList().size()) - } -} diff --git a/libraries/stdlib/test/iterators/FunctionIteratorTest.kt b/libraries/stdlib/test/iterators/FunctionIteratorTest.kt index 8a341a8372a..de5722bcbb1 100644 --- a/libraries/stdlib/test/iterators/FunctionIteratorTest.kt +++ b/libraries/stdlib/test/iterators/FunctionIteratorTest.kt @@ -10,7 +10,7 @@ class FunctionIteratorTest { Test fun iterateOverFunction() { var count = 3 - val iter = stream { + val iter = sequence { count-- if (count >= 0) count else null } @@ -20,7 +20,7 @@ class FunctionIteratorTest { } Test fun iterateOverFunction2() { - 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(arrayListOf(3, 2, 1, 0), values.toList()) } } \ No newline at end of file diff --git a/libraries/stdlib/test/iterators/IteratorsJVMTest.kt b/libraries/stdlib/test/iterators/IteratorsJVMTest.kt index 1a278412de1..e0cb4a4ec74 100644 --- a/libraries/stdlib/test/iterators/IteratorsJVMTest.kt +++ b/libraries/stdlib/test/iterators/IteratorsJVMTest.kt @@ -11,7 +11,7 @@ class IteratorsJVMTest { fun intToBinaryDigits() = { (i: Int) -> val binary = Integer.toBinaryString(i)!! var index = 0 - stream { if (index < binary.length()) binary.get(index++) else null } + sequence { 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()) } } diff --git a/libraries/stdlib/test/iterators/IteratorsTest.kt b/libraries/stdlib/test/iterators/IteratorsTest.kt index b66d28889ef..e6bcc33ee62 100644 --- a/libraries/stdlib/test/iterators/IteratorsTest.kt +++ b/libraries/stdlib/test/iterators/IteratorsTest.kt @@ -5,10 +5,10 @@ import org.junit.Test as test import kotlin.test.fails import java.util.ArrayList -fun fibonacci(): Stream { +fun fibonacci(): Sequence { // fibonacci terms var index = 0; var a = 0; var b = 1 - return stream { when (index++) { 0 -> a; 1 -> b; else -> { val result = a + b; a = b; b = result; result } } } + return sequence { 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("foo", "bar").stream() + val iter = arrayListOf("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 diff --git a/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt index d75a3a4fe78..b75f01f9f8e 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/generators/GenerateCollections.kt @@ -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)) { diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt index 0b8a5d2254c..3f415889211 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Elements.kt @@ -192,7 +192,7 @@ fun elements(): List { 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 { } """ } - body(Streams) { + body(Sequences) { """ val iterator = iterator() if (!iterator.hasNext()) @@ -371,7 +371,7 @@ fun elements(): List { } """ } - body(Streams) { + body(Sequences) { """ val iterator = iterator() if (!iterator.hasNext()) diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt index a4f7a415e47..f015a581ec3 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Engine.kt @@ -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 { - 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() + val deprecates = hashMapOf() var doc: String = "" val docs = HashMap() @@ -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 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" - 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") diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt index 74559ac161d..8afe4ac210e 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Filtering.kt @@ -19,11 +19,11 @@ fun filtering(): List { """ } - doc(Streams) { "Returns a stream containing all elements except first [n] elements" } - returns(Streams) { "Stream" } - body(Streams) { + doc(Sequences) { "Returns a sequence containing all elements except first [n] elements" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return DropStream(this, n) + return DropSequence(this, n) """ } @@ -66,11 +66,11 @@ fun filtering(): List { body(Strings) { "return substring(0, Math.min(n, length()))" } returns(Strings) { "String" } - doc(Streams) { "Returns a stream containing first *n* elements" } - returns(Streams) { "Stream" } - body(Streams) { + doc(Sequences) { "Returns a sequence containing first *n* elements" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return TakeStream(this, n) + return TakeSequence(this, n) """ } @@ -122,12 +122,12 @@ fun filtering(): List { """ } - inline(false, Streams) - doc(Streams) { "Returns a stream containing all elements except first elements that satisfy the given [predicate]" } - returns(Streams) { "Stream" } - body(Streams) { + inline(false, Sequences) + doc(Sequences) { "Returns a sequence containing all elements except first elements that satisfy the given [predicate]" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return DropWhileStream(this, predicate) + return DropWhileSequence(this, predicate) """ } @@ -162,12 +162,12 @@ fun filtering(): List { """ } - inline(false, Streams) - doc(Streams) { "Returns a stream containing first elements satisfying the given [predicate]" } - returns(Streams) { "Stream" } - body(Streams) { + inline(false, Sequences) + doc(Sequences) { "Returns a sequence containing first elements satisfying the given [predicate]" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return TakeWhileStream(this, predicate) + return TakeWhileSequence(this, predicate) """ } } @@ -191,12 +191,12 @@ fun filtering(): List { """ } - inline(false, Streams) - doc(Streams) { "Returns a stream containing all elements matching the given [predicate]" } - returns(Streams) { "Stream" } - body(Streams) { + inline(false, Sequences) + doc(Sequences) { "Returns a sequence containing all elements matching the given [predicate]" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return FilteringStream(this, true, predicate) + return FilteringSequence(this, true, predicate) """ } } @@ -246,12 +246,12 @@ fun filtering(): List { """ } - inline(false, Streams) - doc(Streams) { "Returns a stream containing all elements not matching the given [predicate]" } - returns(Streams) { "Stream" } - body(Streams) { + inline(false, Sequences) + doc(Sequences) { "Returns a sequence containing all elements not matching the given [predicate]" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return FilteringStream(this, false, predicate) + return FilteringSequence(this, false, predicate) """ } } @@ -291,11 +291,11 @@ fun filtering(): List { """ } - doc(Streams) { "Returns a stream containing all elements that are not null" } - returns(Streams) { "Stream" } - body(Streams) { + doc(Sequences) { "Returns a sequence containing all elements that are not null" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return FilteringStream(this, false, { it == null }) as Stream + return FilteringSequence(this, false, { it == null }) as Sequence """ } } diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt index 967b3a017b9..98863c2b67c 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Generators.kt @@ -17,17 +17,17 @@ fun generators(): List { """ } - doc(Streams) { "Returns a stream containing all elements of original stream and then the given element" } - returns(Streams) { "Stream" } - body(Streams) { + doc(Sequences) { "Returns a sequence containing all elements of original sequence and then the given element" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return Multistream(streamOf(this, streamOf(element))) + return MultiSequence(sequenceOf(this, sequenceOf(element))) """ } } templates add f("plus(collection: Iterable)") { - 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") body { @@ -40,7 +40,7 @@ fun generators(): List { } templates add f("plus(array: Array)") { - 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") body { @@ -53,23 +53,23 @@ fun generators(): List { } templates add f("plus(collection: Iterable)") { - only(Streams) - doc { "Returns a stream containing all elements of original stream and then all elements of the given *collection*" } - returns("Stream") + only(Sequences) + doc { "Returns a sequence containing all elements of original sequence and then all elements of the given [collection]" } + returns("Sequence") body { """ - return Multistream(streamOf(this, collection.stream())) + return MultiSequence(sequenceOf(this, collection.sequence())) """ } } - templates add f("plus(stream: Stream)") { - only(Streams) - doc { "Returns a stream containing all elements of original stream and then all elements of the given *stream*" } - returns("Stream") + templates add f("plus(sequence: Sequence)") { + only(Sequences) + doc { "Returns a sequence containing all elements of original sequence and then all elements of the given [sequence]" } + returns("Sequence") body { """ - return Multistream(streamOf(this, stream)) + return MultiSequence(sequenceOf(this, sequence)) """ } } @@ -84,7 +84,7 @@ fun generators(): List { while *second* collection contains elements for which predicate yielded *false* """ } - // TODO: Stream variant + // TODO: Sequence variant returns("Pair, List>") body { """ @@ -119,7 +119,7 @@ fun generators(): List { } templates add f("merge(other: Iterable, 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 { } templates add f("merge(array: Array, 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 { } - templates add f("merge(stream: Stream, transform: (T, R) -> V)") { - only(Streams) + templates add f("merge(sequence: Sequence, 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") + returns("Sequence") body { """ - return MergingStream(this, stream, transform) + return MergingSequence(this, sequence, transform) """ } } templates add f("zip(other: Iterable)") { - 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 { } templates add f("zip(array: Array)") { - 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 { } } - templates add f("zip(stream: Stream)") { - only(Streams) + templates add f("zip(sequence: Sequence)") { + 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>") + returns("Sequence>") body { """ - return MergingStream(this, stream) { (t1, t2) -> t1 to t2 } + return MergingSequence(this, sequence) { (t1, t2) -> t1 to t2 } """ } } diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt index 66c8cf3acf0..07d43bb4a49 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Guards.kt @@ -25,14 +25,14 @@ fun guards(): List { 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 + } as Sequence """ } } diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt index 266815fa57c..77fbd088c5e 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Mapping.kt @@ -16,12 +16,12 @@ fun mapping(): List { """ } - returns(Streams) { "Stream>" } - doc(Streams) { "Returns a stream containing pairs of each element of the original collection and their index" } - body(Streams) { + returns(Sequences) { "Sequence>" } + 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 { """ } - returns(Streams) { "Stream>" } - doc(Streams) { "Returns a stream of [IndexedValue] for each element of the original stream" } - body(Streams) { + returns(Sequences) { "Sequence>" } + 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 { body(Strings) { "return mapIndexedTo(ArrayList(length()), transform)" } - inline(false, Streams) - returns(Streams) { "Stream" } - 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" } + 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 { "return mapTo(ArrayList(), transform)" } - inline(false, Streams) - returns(Streams) { "Stream" } - 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" } + 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 { """ } - 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" } - 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" } + inline(false, Sequences) + body(Sequences) { """ - return TransformingStream(FilteringStream(this, false, { it == null }) as Stream, transform) + return TransformingSequence(FilteringSequence(this, false, { it == null }) as Sequence, transform) """ } } @@ -186,7 +186,7 @@ fun mapping(): List { templates add f("flatMap(transform: (T) -> Iterable)") { 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") @@ -196,19 +196,19 @@ fun mapping(): List { include(Maps) } - templates add f("flatMap(transform: (T) -> Stream)") { - 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)") { + 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") + returns("Sequence") body { - "return FlatteningStream(this, transform)" + "return FlatteningSequence(this, transform)" } } templates add f("flatMapTo(destination: C, transform: (T) -> Iterable)") { 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") @@ -225,11 +225,11 @@ fun mapping(): List { include(Maps) } - templates add f("flatMapTo(destination: C, transform: (T) -> Stream)") { + templates add f("flatMapTo(destination: C, transform: (T) -> Sequence)") { 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") returns("C") diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt index 5180a24e8f9..408f4119539 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Ordering.kt @@ -25,7 +25,7 @@ fun ordering(): List { """ } - exclude(Streams) + exclude(Sequences) } templates add f("sort()") { @@ -44,7 +44,7 @@ fun ordering(): List { """ } - exclude(Streams) + exclude(Sequences) exclude(ArraysOfPrimitives) exclude(ArraysOfObjects) exclude(Strings) @@ -66,7 +66,7 @@ fun ordering(): List { """ } - only(Streams, ArraysOfObjects, ArraysOfPrimitives, Iterables) + only(Sequences, ArraysOfObjects, ArraysOfPrimitives, Iterables) } templates add f("sortDescending()") { @@ -85,7 +85,7 @@ fun ordering(): List { """ } - exclude(Streams) + exclude(Sequences) exclude(ArraysOfPrimitives) exclude(ArraysOfObjects) exclude(Strings) @@ -110,7 +110,7 @@ fun ordering(): List { """ } - exclude(Streams) + exclude(Sequences) exclude(ArraysOfPrimitives) exclude(Strings) } @@ -133,7 +133,7 @@ fun ordering(): List { """ } - 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 { """ } - exclude(Streams) + exclude(Sequences) exclude(ArraysOfPrimitives) exclude(Strings) } @@ -175,7 +175,7 @@ fun ordering(): List { """ } - exclude(Streams) + exclude(Sequences) exclude(ArraysOfPrimitives) exclude(Strings) } diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Sequence.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Sequence.kt new file mode 100644 index 00000000000..a2ed2caff78 --- /dev/null +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Sequence.kt @@ -0,0 +1,50 @@ +package templates + +import templates.Family.* + +fun sequences(): List { + val templates = arrayListOf() + + templates add f("stream()") { + include(Maps) + exclude(Sequences) + deprecate { "Use sequence() instead" } + doc { "Returns a sequence from the given collection" } + returns("Stream") + body { + """ + val sequence = sequence() + return object : Stream { + override fun iterator(): Iterator { + return sequence.iterator() + } + } + """ + } + + } + + templates add f("sequence()") { + include(Maps) + exclude(Sequences) + doc { "Returns a sequence from the given collection" } + returns("Sequence") + body { + """ + return object : Sequence { + override fun iterator(): Iterator { + return this@sequence.iterator() + } + } + """ + } + + body(Sequences) { + """ + return this + """ + } + } + + return templates +} \ No newline at end of file diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Sets.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Sets.kt index a2908c73597..fba02b30868 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Sets.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Sets.kt @@ -6,7 +6,7 @@ fun sets(): List { val templates = arrayListOf() 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") body { @@ -27,7 +27,7 @@ fun sets(): List { } templates add f("distinct()") { - exclude(Strings, Streams) + exclude(Strings, Sequences) doc { "Returns a set containing all distinct elements from the given collection." } returns("Set") @@ -39,7 +39,7 @@ fun sets(): List { } templates add f("union(other: Iterable)") { - exclude(Strings, Streams) + exclude(Strings, Sequences) doc { "Returns a set containing all distinct elements from both collections." } returns("Set") body { @@ -52,7 +52,7 @@ fun sets(): List { } templates add f("intersect(other: Iterable)") { - exclude(Strings, Streams) + exclude(Strings, Sequences) doc { "Returns a set containing all distinct elements from both collections." } returns("Set") body { @@ -65,7 +65,7 @@ fun sets(): List { } templates add f("subtract(other: Iterable)") { - exclude(Strings, Streams) + exclude(Strings, Sequences) doc { "Returns a set containing all distinct elements from both collections." } returns("Set") body { diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt index 05b85b4787c..20e19348ed6 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/Snapshots.kt @@ -41,7 +41,7 @@ fun snapshots(): List { doc { "Returns an ArrayList of all elements" } returns("ArrayList") body { "return toCollection(ArrayList(collectionSizeOrDefault(10)))" } - body(Streams) { "return toCollection(ArrayList())" } + body(Sequences) { "return toCollection(ArrayList())" } body(Strings) { "return toCollection(ArrayList(length()))" } body(ArraysOfObjects, ArraysOfPrimitives) { """ @@ -70,7 +70,7 @@ fun snapshots(): List { doc { "Returns a List containing all elements" } returns("List") body { "return toCollection(ArrayList(collectionSizeOrDefault(10)))" } - body(Streams) { "return toCollection(ArrayList())" } + body(Sequences) { "return toCollection(ArrayList())" } body(Strings) { "return toCollection(ArrayList(length()))" } body(ArraysOfObjects, ArraysOfPrimitives) { """ diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt index f9d9bfdf49f..669f7fa9e21 100644 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt +++ b/libraries/tools/kotlin-stdlib-gen/src/templates/SpecialJVM.kt @@ -102,11 +102,11 @@ fun specialJVM(): List { } exclude(ArraysOfPrimitives, Strings) - doc(Streams) { "Returns a stream containing all elements that are instances of specified class" } - returns(Streams) { "Stream" } - body(Streams) { + doc(Sequences) { "Returns a sequence containing all elements that are instances of specified class" } + returns(Sequences) { "Sequence" } + body(Sequences) { """ - return FilteringStream(this, true, { klass.isInstance(it) }) as Stream + return FilteringSequence(this, true, { klass.isInstance(it) }) as Sequence """ } } @@ -140,13 +140,13 @@ fun specialJVM(): List { } exclude(ArraysOfPrimitives, Strings) - doc(Streams) { "Returns a stream containing all elements that are instances of specified type parameter R" } - returns(Streams) { "Stream" } + doc(Sequences) { "Returns a sequence containing all elements that are instances of specified type parameter R" } + returns(Sequences) { "Sequence" } inline(true) receiverAsterisk(true) - body(Streams) { + body(Sequences) { """ - return FilteringStream(this, true, { it is R }) as Stream + return FilteringSequence(this, true, { it is R }) as Sequence """ } } diff --git a/libraries/tools/kotlin-stdlib-gen/src/templates/Stream.kt b/libraries/tools/kotlin-stdlib-gen/src/templates/Stream.kt deleted file mode 100644 index e6b1c7abb85..00000000000 --- a/libraries/tools/kotlin-stdlib-gen/src/templates/Stream.kt +++ /dev/null @@ -1,30 +0,0 @@ -package templates - -import templates.Family.* - -fun streams(): List { - val templates = arrayListOf() - - templates add f("stream()") { - include(Maps) - doc { "Returns a stream from the given collection" } - returns("Stream") - body { - """ - return object : Stream { - override fun iterator(): Iterator { - return this@stream.iterator() - } - } - """ - } - - body(Streams) { - """ - return this - """ - } - } - - return templates -} \ No newline at end of file