How can I find the index of the maximum value in a List in Scala?

Phil picture Phil · Dec 23, 2012 · Viewed 15.9k times · Source

For a Scala List[Int] I can call the method max to find the maximum element value.

How can I find the index of the maximum element?

This is what I am doing now:

val max = list.max 
val index = list.indexOf(max)

Answer

Travis Brown picture Travis Brown · Dec 23, 2012

One way to do this is to zip the list with its indices, find the resulting pair with the largest first element, and return the second element of that pair:

scala> List(0, 43, 1, 34, 10).zipWithIndex.maxBy(_._1)._2
res0: Int = 1

This isn't the most efficient way to solve the problem, but it's idiomatic and clear.