1. Overview

In this tutorial, we’ll see how to get the index of the element with the maximum value in a Scala List.

2. Using a Loop

The most naive solution we could consider would be to manually iterate through the List and keep the max element and its index stored. As we find a bigger element, we update both of them:

scala> val lst = List(1,2,3,2,1)
lst: List[Int] = List(1, 2, 3, 2, 1)

scala> var maxIndex = 0
maxIndex: Int = 0

scala> var maxValue = lst(0)
maxValue: Int = 1

scala> for(idx <- 1 until lst.size) {
     |   if (lst(idx) > maxValue) {
     |           maxIndex = idx
     |           maxValue = lst(idx)
     |   }
     | }

scala> maxIndex
res1: Int = 2

scala> maxValue
res2: Int = 3

This solution is able to return the max value and its index. If we have duplicated elements in the List, it returns the index of the first occurrence. We can change it to return the last occurrence by modifying the condition in the if block:

scala> val lst = List(1,2,3,2,3,1)
lst: List[Int] = List(1, 2, 3, 2, 3, 1)

scala> var maxIndex = 0
maxIndex: Int = 0

scala> var maxValue = lst(0)
maxValue: Int = 1

scala> for(idx <- 1 until lst.size) {
     |   if (lst(idx) >= maxValue) {
     |           maxIndex = idx
     |           maxValue = lst(idx)
     |   }
     | }

scala> maxIndex
res1: Int = 4

scala> maxValue
res2: Int = 3

3. Using List.max() Method

In order to avoid such a lengthy solution, we can make use of some existing Scala methods. Two methods that can be very useful are List.max() and List.indexOf():

scala> val max = lst.max
max: Int = 3

scala> val idx = lst.indexOf(max)
idx: Int = 2

The List.max() method finds the biggest element in the List, while the List.indexOf() finds the first occurrence of the given element. This solution is much cleaner than the previous approach, even though it iterates on the List twice.

4. Using List.zipWithIndex() Method

Another possible solution is to use the List.zipWithIndex() method, and then find the pair with the maximum value:

scala> lst.zipWithIndex
res0: List[(Int, Int)] = List((1,0), (2,1), (3,2), (2,3), (1,4))

scala> lst.zipWithIndex.maxBy(pair => pair._1)
res1: (Int, Int) = (3,2)

scala> lst.zipWithIndex.maxBy(pair => pair._1)._2
res2: Int = 2

We start by zipping the original List elements with their corresponding index. Then we can find the max pair by the given List value. Finally, we extract the index from the max pair.

5. Conclusion

In this article, we saw how to get the index of the element with the maximum value in a Scala List.

We started with a naive approach using a for loop. Then, we moved into a less extensive solution that uses the existing List.max() and List.indexOf() methods.

Finally, we looked into a more idiomatic solution that zips the original list with the corresponding indexes and gets the max pair.

Comments are closed on this article!