Kotlin - Get Maximum value in ArrayList of Ints

Sushobh Nadiger :

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)

Now i want to get Max 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?

s1m0nw1 :

You can use built-in functionality:

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=464596&siteId=1