The minWith() extension function in Kotlin returns the first element having the smallest value according to the provided comparator.
The syntax of Set.minWith() extension function is:
fun <T> Set<T>.minWith(comparator: Comparator<in T>): T
fun <T> Set<T>.minWith(comparator: Comparator<in T>): T?
This minWith() extension function of Set returns the first element having the smallest value according to the provided comparator.
Parameter | Optional/Required | Description |
---|---|---|
comparator | required | The comparator used to compare the elements. |
Set.minWith() returns value of type T
or T?
.
Using minWith() to find the minimum element in a set of integers with a custom comparator.
For example,
fun main() {
val numbers = setOf(3, 1, 4, 1, 5)
val minNumber = numbers.minWith(compareBy { it })
println(minNumber)
}
1
Using minWith() to find the minimum string in a set based on length with a custom comparator.
For example,
fun main() {
val strings = setOf("apple", "pear", "banana")
val shortestString = strings.minWith(compareBy { it.length })
println(shortestString)
}
pear
Using minWith() to find the minimum custom object in a set based on a property with a custom comparator.
For example,
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.minWith(compareBy { it.age })
println(youngestPerson)
}
Person(name=Bob, age=25)
In this Kotlin tutorial, we learned about minWith() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.