To slice the last N elements from a list in Kotlin, you can use the takeLast
function.
In this example,
numbers
with integer values.takeLast
function on the list object numbers
to take the last N elements.fun main() {
val numbers = listOf(1, 2, 3, 4, 5)
val n = 3
val slicedNumbers = numbers.takeLast(n)
println("Sliced list: $slicedNumbers")
}
Sliced list: [3, 4, 5]
In this example,
words
with string values.takeLast
function on the list object words
to take the last N elements.fun main() {
val words = listOf("apple", "banana", "cherry", "date", "elderberry")
val n = 2
val slicedWords = words.takeLast(n)
println("Sliced list: $slicedWords")
}
Sliced list: [date, elderberry]
In this tutorial, we learned How to Slice Last N Elements from a List in Kotlin language with well detailed examples.