Kotlin Set minOf()
Syntax & Examples


Set.minOf() extension function

The minOf() extension function in Kotlin returns the smallest value among all values produced by the selector function applied to each element in the collection.


Syntax of Set.minOf()

The syntax of Set.minOf() extension function is:

fun <T> Set<T>.minOf(selector: (T) -> Double): Double

This minOf() extension function of Set returns the smallest value among all values produced by selector function applied to each element in the collection.

Parameters

ParameterOptional/RequiredDescription
selectorrequiredA function that takes an element and returns a Double value to be compared.

Return Type

Set.minOf() returns value of type Double.



✐ Examples

1 Finding the minimum value among integers transformed to double

Using minOf() to find the minimum value among integers in a set transformed to double.

For example,

  1. Create a set of integers.
  2. Use minOf() with a selector function that transforms each integer to double.
  3. Print the resulting minimum value.

Kotlin Program

fun main() {
    val numbers = setOf(3, 1, 4, 1, 5)
    val minValue = numbers.minOf { it.toDouble() }
    println(minValue)
}

Output

1.0

2 Finding the minimum length of strings

Using minOf() to find the minimum length among strings in a set.

For example,

  1. Create a set of strings.
  2. Use minOf() with a selector function that returns the length of each string as a double.
  3. Print the resulting minimum length.

Kotlin Program

fun main() {
    val strings = setOf("apple", "pear", "banana")
    val minLength = strings.minOf { it.length.toDouble() }
    println(minLength)
}

Output

4.0

3 Finding the minimum age among custom objects

Using minOf() to find the minimum age among custom objects in a set.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use minOf() with a selector function that returns the age of each object as a double.
  4. Print the resulting minimum age.

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 minAge = people.minOf { it.age.toDouble() }
    println(minAge)
}

Output

25.0

Summary

In this Kotlin tutorial, we learned about minOf() extension function of Set: the syntax and few working examples with output and detailed explanation for each example.