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)
}
CodePudding user response:
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.