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

ParameterOptional/RequiredDescription
nrequiredThe 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,

  1. Create a set of integers.
  2. Use take() with n=3 to get the first 3 elements.
  3. 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,

  1. Create a set of strings.
  2. Use take() with n=2 to get the first 2 elements.
  3. 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,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use take() with n=1 to get the first element.
  4. 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.