alturkovic
alturkovic

Reputation: 1140

Kotlin MutableList.take in place?

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).

Upvotes: 1

Views: 163

Answers (2)

alturkovic
alturkovic

Reputation: 1140

Another way this might be achieved:

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

Upvotes: 1

Sweeper
Sweeper

Reputation: 274423

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()

Upvotes: 4

Related Questions