Finding the index of an element in a list scala

2020-05-19 06:27发布

问题:

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"

回答1:

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

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



回答2:

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

val ls = List("Mary", "had", "a", "little", "lamb","a")
ls.indexWhere(_.size <= 3)

This returns 1, since "had" is the first word with at most 3 letters.



回答3:

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)


标签: list scala