Kotlin - Get Maximum value in ArrayList of Ints

You can use max(), if you want to use the default comparison (as in your case with ints), or maxBy, if you want to use a custom selector (i.e., algorithm) to compare values.

Note that both return int? (in your case), since the collection might be empty (i.e., no maximum value is present)


max() becomes deprecated starting from Kotlin 1.4, please use maxOrNull()

val list = listOf(10, 2, 33)
val max: Int = list.maxOrNull() ?: 0

You can use built-in functionality with maxOrNull (docs):

val amplitudes = listOf(1,2,3,4,3,2,1)
val max = amplitudes.maxOrNull() ?: 0

Tags:

Kotlin