Reputation: 8841
I have this ArrayList
var amplititudes: ArrayList<Int> = ArrayList()
amplititudes.add(1)
amplititudes.add(2)
amplititudes.add(3)
amplititudes.add(4)
amplititudes.add(3)
amplititudes.add(2)
amplititudes.add(1)
I want to get the maximum value i.e 4. What will be the easiest way to find the max element? I know about the max()
method , but it will forces me to use ?
with the return value since it could be null
. Is there any solution which is better than this?
Upvotes: 45
Views: 58560
Reputation: 3429
max()
deprecated in Kotlin 1.4.
But it was reintroduced in 1.7 . More details here
Both max()
and maxOrNull()
can be used.
The difference is,
max()
returns non null values.If the collection is empty it will throw NoSuchElementException.
maxOrNull()
returns a nullable value, so if element not present in collection it would return null.
If you are sure that collection will not be empty or you have handled exception, you can use max()
.Otherwise it is recommended is to use maxOrNull()
and have default value if it returns null.
val amplitudes = listOf(10,8,20,15,30,90)
//Here it returns non-null int
val max:Int = amplitudes.max()
println(max) //90
//Here it returns nullable int
val max :Int? = amplitudes.maxOrNull()
println(max) //90
//Here we can make it as non-nullable type using elvis operator.
val max1 :Int = amplitudes.maxOrNull()?:0
println(max) //90
val amplitudes1 = listOf<Int>()
val max2 :Int? = amplitudes1.maxOrNull()
println(max2) //prints null
val max3:Int = amplitudes1.max()
println(max3) // Throws NoSuchElementException
Upvotes: 4
Reputation: 81879
You can use built-in functionality with maxOrNull
(docs):
val amplitudes = listOf(1,2,3,4,3,2,1)
val max = amplitudes.maxOrNull() ?: 0
Upvotes: 49
Reputation: 3261
max()
becomes deprecated starting from Kotlin 1.4, please use maxOrNull()
val list = listOf(10, 2, 33)
val max: Int = list.maxOrNull() ?: 0
Upvotes: 15
Reputation: 10704
You can use max()
, if you want to use the default comparison (as in your case with int
s), 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)
Upvotes: 3