Kotlin Set minByOrNull()
Syntax & Examples
Set.minByOrNull() extension function
The minByOrNull() extension function in Kotlin returns the first element yielding the smallest value of the given function, or null if there are no elements.
Syntax of Set.minByOrNull()
The syntax of Set.minByOrNull() extension function is:
fun <T, R : Comparable<R>> Set<T>.minByOrNull(selector: (T) -> R): T?
This minByOrNull() extension function of Set returns the first element yielding the smallest value of the given function or null if there are no elements.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
selector | required | A function that takes an element and returns the value to be compared. |
Return Type
Set.minByOrNull() returns value of type T?
.
✐ Examples
1 Finding the minimum element by a property in a set of integers
Using minByOrNull() to find the minimum element in a set of integers.
For example,
- Create a set of integers.
- Use minByOrNull() with a selector function that returns the element itself.
- Print the resulting element.
Kotlin Program
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minNumber = numbers.minByOrNull { it }
println(minNumber)
}
Output
1
2 Finding the string with the minimum length in a set
Using minByOrNull() to find the string with the minimum length in a set.
For example,
- Create a set of strings.
- Use minByOrNull() with a selector function that returns the length of each string.
- Print the resulting string.
Kotlin Program
fun main() {
val strings = setOf("apple", "pear", "banana")
val shortestString = strings.minByOrNull { it.length }
println(shortestString)
}
Output
pear
3 Finding the custom object with the minimum age in a set
Using minByOrNull() to find the custom object with the minimum age in a set.
For example,
- Create a data class.
- Create a set of custom objects.
- Use minByOrNull() with a selector function that returns the age of each object.
- Print the resulting object.
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 youngestPerson = people.minByOrNull { it.age }
println(youngestPerson)
}
Output
Person(name=Bob, age=25)
4 Handling an empty set
Using minByOrNull() to handle an empty set and return null.
For example,
- Create an empty set of integers.
- Use minByOrNull() with a selector function that returns the element itself.
- Print the resulting element or null.
Kotlin Program
fun main() {
val emptySet = emptySet<Int>()
val minNumber = emptySet.minByOrNull { it }
println(minNumber)
}
Output
null
Summary
In this Kotlin tutorial, we learned about minByOrNull() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.