In this short tutorial, we’re going to see how to find the index of an element in a List in Scala.
2. Using indexOf and lastIndexOf
The first thing we need to take into account is that a list allows duplicated elements. Secondly, the methods available in the List class only return the index of one occurrence of the element. Depending on the method we use, it’ll be the first or the last. Let’s start by using the indexOf method to retrieve the first occurrence:
scala> List(1,2,3,2,1).indexOf(2) res1: Int = 1
If we look for an element that does not exist, the result will be -1:
scala> List(1,2,3,2,1).indexOf(5) res2: Int = -1
We can also find the index of the last occurrence of the element. To do that, we should use the lastIndexOf method:
scala> List(1,2,3,2,1).lastIndexOf(2) res3: Int = 3
Just as the indexOf method, if the element does not exist in the list, it will return -1.
3. Using indexWhere and lastIndexWhere
If we need a more complex logic, we can use the indexWhere and lastIndexWhere methods instead:
scala> List(1,2,3,4,5,6).indexWhere(element => element > 3) res4: Int = 3 scala> List(1,2,3,4,5,6).lastIndexWhere(element => element > 3) res5: Int = 5
Both methods receive a predicate and retrieve the first or last index of the element that satisfies the predicate. Once again, if the element is not present, these methods will return -1.
4. Finding All Indexes
Finally, what if we wanted to find all the indexes of the element? In that case, there’s no out-of-the-box solution, so we need to be more creative. This solution chains several operations to achieve our goal:
scala> List(1,2,3,2,1).zipWithIndex.filter(pair => pair._1 == 2).map(pair => pair._2) res6: List[Int] = List(1, 3)
We start by using the zipWithIndex method which will turn our list into a list of pairs. Each pair is made of the original element and its index on the original list.
We then filter the pairs to keep only those where the first element (the original) is the same as the one we’re looking for.
Finally, we use the map operation to extract from the pair the original element, removing the index we added in the first place by using the zipWithIndex method.
In this tutorial, we saw how to find an element of a list in Scala. We saw that there are out-of-the-box methods in the core library to find the first and last occurrences of the element. We also saw that if we want to find all the occurrences, we need to do a little more work. This can be done by leveraging several Scala language methods.