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

ParameterOptional/RequiredDescription
selectorrequiredA 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,

  1. Create a set of integers.
  2. Use minByOrNull() with a selector function that returns the element itself.
  3. 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,

  1. Create a set of strings.
  2. Use minByOrNull() with a selector function that returns the length of each string.
  3. 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,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use minByOrNull() with a selector function that returns the age of each object.
  4. 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,

  1. Create an empty set of integers.
  2. Use minByOrNull() with a selector function that returns the element itself.
  3. 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.