Surya Tej
Surya Tej

Reputation: 1392

Pop Mutablelist from a MutableList kotlin

I have a mutableListOf<MutableList<Int>> in kotlin. How do I pop the last element out of this list? I have tried removeAt but it didn't work.

fun main() {
    val intervals:List<List<Int>> = listOf(listOf(2,9), listOf(1,8), listOf(-4, 234), listOf(22,1))
    println(intervals)    
    var sortedIntervals = intervals.toMutableList().sortedWith(Comparator<List<Int>> 
            {a, b -> a[0].compareTo(b[0])})
    println(sortedIntervals)
    sortedIntervals = sortedIntervals.map() {it -> it.toMutableList()}
    println(sortedIntervals.last())
    sortedIntervals.removeAt(sortedIntervals.size-1)
    println(sortedIntervals)
}

Upvotes: 2

Views: 1388

Answers (1)

Sergio
Sergio

Reputation: 30705

You can use removeLastOrNull() or removeLast() functions:

// sortedIntervals must be MutableList to call removeLastOrNull() or removeLast()
val sortedIntervals: MutableList<...> = ...
sortedIntervals.removeLastOrNull()

The difference between them is that removeLast() function throws NoSuchElementException if this list is empty, but removeLastOrNull() doesn't throw an exception, it returns null if this list is empty.

Upvotes: 5

Related Questions