Kotlin Tutorials

Kotlin Set minWith()
Syntax & Examples

Set.minWith() extension function

The minWith() extension function in Kotlin returns the first element having the smallest value according to the provided comparator.


Syntax of Set.minWith()

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.

Parameters

ParameterOptional/RequiredDescription
comparatorrequiredThe comparator used to compare the elements.

Return Type

Set.minWith() returns value of type T or T?.



✐ Examples

1 Finding the minimum element in a set of integers with a custom comparator

Using minWith() to find the minimum element in a set of integers with a custom comparator.

For example,

  1. Create a set of integers.
  2. Use minWith() with a custom comparator to find the minimum element.
  3. Print the resulting element.

Kotlin Program

fun main() {
    val numbers = setOf(3, 1, 4, 1, 5)
    val minNumber = numbers.minWith(compareBy { it })
    println(minNumber)
}

Output

1

2 Finding the minimum string in a set based on length with a custom comparator

Using minWith() to find the minimum string in a set based on length with a custom comparator.

For example,

  1. Create a set of strings.
  2. Use minWith() with a custom comparator to find the minimum string based on length.
  3. Print the resulting string.

Kotlin Program

fun main() {
    val strings = setOf("apple", "pear", "banana")
    val shortestString = strings.minWith(compareBy { it.length })
    println(shortestString)
}

Output

pear

3 Finding the minimum custom object in a set based on a property with a custom comparator

Using minWith() to find the minimum custom object in a set based on a property with a custom comparator.

For example,

  1. Create a data class.
  2. Create a set of custom objects.
  3. Use minWith() with a custom comparator to find the minimum object based on a property.
  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.minWith(compareBy { it.age })
    println(youngestPerson)
}

Output

Person(name=Bob, age=25)

Summary

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.