Finding the index of an element in a list scala

ListScala

List Problem Overview


How do I find the index of an element in a Scala list.

val ls = List("Mary", "had", "a", "little", "lamb")

I need to get 3 if I ask for the index of "little"

List Solutions


Solution 1 - List

scala> List("Mary", "had", "a", "little", "lamb").indexOf("little")
res0: Int = 3

You might try reading the scaladoc for List next time. ;)

Solution 2 - List

If you want to search by a predicate, use .indexWhere(f):

val ls = List("Mary", "had", "a", "little", "lamb","a")
ls.indexWhere(_.startsWith("l"))

This returns 3, since "little" is the first word beginning with letter l.

Solution 3 - List

If you want list of all indices containing "a", then:

val ls = List("Mary", "had", "a", "little", "lamb","a")
scala> ls.zipWithIndex.filter(_._1 == "a").map(_._2)
res13: List[Int] = List(2, 5)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionyAsHView Question on Stackoverflow
Solution 1 - ListDaoWenView Answer on Stackoverflow
Solution 2 - ListRok KraljView Answer on Stackoverflow
Solution 3 - ListJatinView Answer on Stackoverflow