Kotlin Set first()
Syntax & Examples
Set.first() extension function
The first() extension function in Kotlin returns the first element in a set. If a predicate is provided, it returns the first element that matches the given predicate.
Syntax of Set.first()
There are 2 variations for the syntax of Set.first() extension function. They are:
fun <T> Set<T>.first(): T
This extension function returns the first element.
Returns value of type T
.
fun <T> Set<T>.first(predicate: (T) -> Boolean): T
This extension function returns the first element matching the given predicate.
Returns value of type T
.
✐ Examples
1 Getting the first element
Using first() to get the first element in a set.
For example,
- Create a set of integers.
- Use first() to get the first element in the set.
- Print the resulting element.
Kotlin Program
fun main() {
val numbers = setOf(1, 2, 3, 4, 5)
val firstNumber = numbers.first()
println(firstNumber)
}
Output
1
2 Getting the first even number
Using first() to get the first even number in a set.
For example,
- Create a set of integers.
- Define a predicate function that returns true for even numbers.
- Use first() to get the first even number in the set.
- Print the resulting number.
Kotlin Program
fun main() {
val numbers = setOf(1, 3, 5, 6, 7, 8)
val firstEven = numbers.first { it % 2 == 0 }
println(firstEven)
}
Output
6
3 Getting the first string with length greater than 2
Using first() to get the first string with a length greater than 2 in a set.
For example,
- Create a set of strings.
- Define a predicate function that returns true for strings with a length greater than 2.
- Use first() to get the first string with a length greater than 2 in the set.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("a", "ab", "abc", "abcd")
val firstLongString = strings.first { it.length > 2 }
println(firstLongString)
}
Output
"abc"
Summary
In this Kotlin tutorial, we learned about first() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.