2

Assuming that I'm working with a lazy sequence and sort of an infinite sequence, then I try to write something like (pseudo code):

Sequence([1,2,3,...])
   .sortDescending()
   .take(10);

In this scenario, I'm sorting first and then taking 10 elements. How would sorting function perform on an infinite sequence?

An example would be Kotlin sequence: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/sorted.html

Afshin Mehrabani
  • 33,262
  • 29
  • 136
  • 201

1 Answers1

1

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) }
s1m0nw1
  • 76,759
  • 17
  • 167
  • 196