Kotlin Set drop()
Syntax & Examples
Set.drop() extension function
The drop() extension function for sets in Kotlin returns a list containing all elements of the set except the first n elements.
Syntax of Set.drop()
The syntax of Set.drop() extension function is:
fun <T> Set<T>.drop(n: Int): List<T>
This drop() extension function of Set returns a list containing all elements except the first n elements.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
n | required | The number of elements to drop from the beginning of the set. |
Return Type
Set.drop() returns value of type List
.
✐ Examples
1 Using drop() to skip the first 2 elements of a set
In Kotlin, we can use the drop()
function to get a list of elements from a set, excluding the first 2 elements.
For example,
- Create a set of integers.
- Use the
drop()
function to skip the first 2 elements. - Print the resulting list to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val numbers = setOf(1, 2, 3, 4, 5)
val droppedNumbers = numbers.drop(2)
println("Elements after dropping the first 2: $droppedNumbers")
}
Output
Elements after dropping the first 2: [3, 4, 5]
2 Using drop() with a set of strings
In Kotlin, we can use the drop()
function to get a list of elements from a set of strings, excluding the first 3 elements.
For example,
- Create a set of strings.
- Use the
drop()
function to skip the first 3 elements. - Print the resulting list to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val fruits = setOf("apple", "banana", "cherry", "date", "elderberry")
val droppedFruits = fruits.drop(3)
println("Elements after dropping the first 3: $droppedFruits")
}
Output
Elements after dropping the first 3: [date, elderberry]
3 Using drop() with an empty set
In Kotlin, we can use the drop()
function on an empty set, which will return an empty list regardless of the number of elements to drop.
For example,
- Create an empty set of integers.
- Use the
drop()
function to skip the first 2 elements. - Print the resulting list to the console using the
println
function.
Kotlin Program
fun main(args: Array<String>) {
val emptySet = emptySet<Int>()
val droppedElements = emptySet.drop(2)
println("Elements after dropping the first 2 in empty set: $droppedElements")
}
Output
Elements after dropping the first 2 in empty set: []
Summary
In this Kotlin tutorial, we learned about drop() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.