Kotlin List take()
Syntax & Examples
Syntax of List.take()
The syntax of List.take() extension function is:
fun <T> Iterable<T>.take(n: Int): List<T>
This take() extension function of List returns a list containing first n elements.
✐ Examples
1 Example
In this example,
- We create a list named
list
containing the integers1, 2, 3, 4, 5
. - We call the
take
function onlist
with parameter3
, which returns the first 3 elements of the list. - The result, which is a list containing
1, 2, 3
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5);
val result = list.take(3);
println(result);
}
Output
[1, 2, 3]
2 Example
In this example,
- We create a list named
list
containing the characters'a', 'p', 'p', 'l', 'e'
. - We call the
take
function onlist
with parameter2
, which returns the first 2 elements of the list. - The result, which is a list containing
'a', 'p'
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("a", "p", "p", "l", "e");
val result = list.take(2);
println(result);
}
Output
[a, p]
3 Example
In this example,
- We create a list named
list
containing the strings"apple", "banana", "cherry", "date", "elderberry"
. - We call the
take
function onlist
with parameter4
, which returns the first 4 elements of the list. - The result, which is a list containing
"apple", "banana", "cherry", "date"
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprintln
function.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "cherry", "date", "elderberry");
val result = list.take(4);
println(result);
}
Output
[apple, banana, cherry, date]
Summary
In this Kotlin tutorial, we learned about take() extension function of List: the syntax and few working examples with output and detailed explanation for each example.