61

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"

yAsH
  • 3,367
  • 8
  • 36
  • 67

3 Answers3

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

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

DaoWen
  • 32,589
  • 6
  • 74
  • 101
52

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.

Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
40

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)
prosseek
  • 182,215
  • 215
  • 566
  • 871
Jatin
  • 31,116
  • 15
  • 98
  • 163
  • 23
    Interesting! I think this is what _collect_ is for though: `ls.zipWithIndex.collect { case ("a",i) => i }` – DaoWen Jul 26 '13 at 17:04
  • 1
    Is there a way to use `.collect` with a variable ? Like `ls.zipWithIndex.collect { case (someVariableIWantToMatch,i) => i }` ? – Arthur Attout Mar 07 '19 at 09:30
  • 2
    Nevermind, that's about [Stable identifiers](https://stackoverflow.com/questions/7078022/why-does-pattern-matching-in-scala-not-work-with-variables) – Arthur Attout Mar 07 '19 at 10:04