假设我正在处理一个懒惰的序列和一个无限序列,那么我尝试编写类似(伪代码)的东西:
Sequence([1,2,3,...])
.sortDescending()
.take(10);
在这种情况下,我先排序,然后选择10
元素。排序函数如何在无限序列上执行?
一个例子是Kotlin序列:https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/sorted.html
答案 0 :(得分:1)
sortDescending
方法将相应的序列转换为MutableList
,正在对其进行排序,然后转换回新的序列。以下显示了内部使用的sortedWith
函数:
/**
* Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
* The operation is _intermediate_ and _stateful_.
*/
public fun <T> Sequence<T>.sortedWith(comparator: Comparator<in T>): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
val sortedList = this@sortedWith.toMutableList()
sortedList.sortWith(comparator)
return sortedList.iterator()
}
}
}
所以当你有一个无限的序列时,例如:
generateSequence(1) {
it * 2
}
并且您在该序列上调用所描述的函数(以及终止函数,如forEach { println(it) }
),所有元素都会在某个时刻被添加到列表中,这肯定会由于无限循环而失败:
java.lang.OutOfMemoryError: Java heap space
你可能想要像这里那样对固定数量的元素进行排序:
generateSequence(1) {
it * 2
}.take(10)
.sortedDescending()
.forEach { println(it) }