The sortDescending
method converts the corresponding sequence into a MutableList
, which is being sorted and then converted back into a new sequence. The following shows the internally used sortedWith
function:
/**
* 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()
}
}
}
So when you have an infinite sequence, such as:
generateSequence(1) {
it * 2
}
and you invoke the depicted function on that sequence (as well as a terminate function like forEach { println(it) }
), all elements will at some point be added into the list, which most certainly will fail due to an infinite loop:
java.lang.OutOfMemoryError: Java heap space
You'll probably want to sort a fixed number of elements like here:
generateSequence(1) {
it * 2
}.take(10)
.sortedDescending()
.forEach { println(it) }