Finding the index of an element in a list scala

前端 未结 3 2026
名媛妹妹
名媛妹妹 2021-02-01 12:37

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 f

相关标签:
3条回答
  • 2021-02-01 13:11
    scala> List("Mary", "had", "a", "little", "lamb").indexOf("little")
    res0: Int = 3
    

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

    0 讨论(0)
  • 2021-02-01 13:16

    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)
    
    0 讨论(0)
  • 2021-02-01 13:18

    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.

    0 讨论(0)
提交回复
热议问题