Home > other >  Kotlin MutableList.take in place?
Kotlin MutableList.take in place?

Time:10-01

I have managed to removeAll from a MutableList in-place successfully. This call modifies the receiver list to remove all elements matching the given predicate.

I would like to modify the receiver list by keeping only the first n elements but I cannot figure out how to do it since take and slice calls return a new collection.

Is there an in-place version of take or slice functions on MutableList?

An example of how I would like to use the new function: myList.keepFirst(5).

CodePudding user response:

For keepFirst(n) and keepLast(n), you can get a subList(), then clear() it. This works because subList returns a "view" of the list, not a copy.

// suppose "l" is a MutableList
// keepFirst(5)
l.subList(5, l.size).clear()
// keepLast(5)
l.subList(0, l.size - 5).clear()

CodePudding user response:

Another way this might be achieved:

private fun <T> MutableList<T>.keepFirst(n: Int) {
    while (size > n) {
        removeLast()
    }
}
  • Related