Kotlin Set take()
Syntax & Examples
Set.take() extension function
The take() extension function in Kotlin returns a list containing the first n elements.
Syntax of Set.take()
The syntax of Set.take() extension function is:
fun <T> Set<T>.take(n: Int): List<T>
This take() extension function of Set returns a list containing first n elements.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
n | required | The number of elements to take from the beginning. |
Return Type
Set.take() returns value of type List
.
✐ Examples
1 Taking the first 3 elements of a set of integers
Using take() to get the first 3 elements of a set of integers.
For example,
- Create a set of integers.
- Use take() with n=3 to get the first 3 elements.
- Print the resulting list.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val firstThree = numbers.take(3)
println(firstThree)
}
Output
[1, 2, 3]
2 Taking the first 2 elements of a set of strings
Using take() to get the first 2 elements of a set of strings.
For example,
- Create a set of strings.
- Use take() with n=2 to get the first 2 elements.
- Print the resulting list.
Kotlin Program
fun main() {
val strings = setOf("one", "two", "three", "four")
val firstTwo = strings.take(2)
println(firstTwo)
}
Output
[one, two]
3 Taking the first element of a set of custom objects
Using take() to get the first element of a set of custom objects.
For example,
- Create a data class.
- Create a set of custom objects.
- Use take() with n=1 to get the first element.
- Print the resulting list.
Kotlin Program
data class Person(val name: String, val age: Int)
fun main() {
val people = setOf(Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35))
val firstPerson = people.take(1)
println(firstPerson)
}
Output
[Person(name=Alice, age=30)]
Summary
In this Kotlin tutorial, we learned about take() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.