In Kotlin, filtering an immutable list (read-only list) does not require creating additional copies. The filter function in Kotlin already creates a new list with the elements that match the given predicate, so the original list remains unaltered. However, please note that each time you use the filter function, a new list is created with matching elements. Naive approach of chaining multiple filter operations on a list can prove inefficient. This post suggests a tiny optimization that can lead to improved performance.
If you want to perform several filtering operations without creating multiple lists, you might consider transforming your read-only list to a Sequence
using the asSequence
function. Then perform your operations on the sequence, which is a more memory-efficient operation. After all operations are done, you can transform it back to a list.
Here is an example:
val numbers = listOf("one", "two", "three", "four")
val filteredNumbers = numbers.asSequence()
.filter { it.length > 3 }
.filter { it.startsWith("t") }
.toList() // Convert sequence back to list
In this example, you only create a single new list after performing all filtering operations on the sequence.
Another benefit of converting a list to a sequence is that sequences are lazily evaluated. Meaning, the elements are computed on-the-fly as needed which can boost performance especially when dealing with large collections.