DEV Community

loizenai
loizenai

Posted on

Kotlin List methods – max() maxBy() maxWith() example

https://grokonez.com/kotlin/kotlin-list-methods-max-maxby-maxwith

Kotlin List methods – max() maxBy() maxWith() example

In the tutorial, JavaSampleApproach will show how to use Kotlin List methods max(), maxBy(), maxWith().

I. Kotlin List methods - max() maxBy() maxWith()

1. max()

max() is used to return the largest element of an Iterable. It will return 'null' if there are no element.
Method signature:


// 1.   
public fun Iterable.max(): Double?

// 2.
public fun Iterable.max(): Float?

Practice:


val simpleList = listOf(1.99, 55.4, 20.0, 99.99, 23.0, 34.2, 88.0, 72.1, 61.2, 43.9)

// public fun Iterable.max(): Double?
val largestElement = simpleList.max()
println(largestElement)
// ->
/*
    99.99
*/

2. maxBy()

maxBy() returns the first element having largest value of the given function selector: (T) -> R or 'null' if there are no elements.
Method signature:

https://grokonez.com/kotlin/kotlin-list-methods-max-maxby-maxwith

Kotlin List methods – max() maxBy() maxWith() example

Top comments (0)