Kotlin Set maxWith()
Syntax & Examples


Set.maxWith() extension function

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


Syntax of Set.maxWith()

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

fun <T> Set<T>.maxWith(comparator: Comparator<in T>): T
fun <T> Set<T>.maxWith(comparator: Comparator<in T>): T?

This maxWith() extension function of Set returns the first element having the largest value according to the provided comparator.

Parameters

ParameterOptional/RequiredDescription
comparatorrequiredThe comparator used to compare the elements.

Return Type

Set.maxWith() returns value of type T, or T?.



✐ Examples

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

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

For example,

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

Kotlin Program

fun main() {
    val numbers = setOf(1, 2, 3, 4, 5)
    val maxNumber = numbers.maxWith(compareBy { it })
    println(maxNumber)
}

Output

5

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

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

For example,

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

Kotlin Program

fun main() {
    val strings = setOf("one", "two", "three")
    val maxLengthString = strings.maxWith(compareBy { it.length })
    println(maxLengthString)
}

Output

three

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

Using maxWith() to find the maximum 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 maxWith() with a custom comparator to find the maximum 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 oldestPerson = people.maxWith(compareBy { it.age })
    println(oldestPerson)
}

Output

Person(name=Charlie, age=35)

Summary

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