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