For example:
import scala.collection.mutable.ArrayBuffer
val times = ArrayBuffer(Some("Last week"), Some("Last month"), Some("Last year"))
How do I find the index of Last year/Last month/... in this array buffer?
You can use indexOf
times.indexOf(Some("Last month")) // returns 1
You can convert the times ArrayBuffer[Option[String]] into a ArrayBuffer[String] via
val l = times.map(_.getOrElse("")) // ArrayBuffer("Last week", "Last month", ...)
And then you can search for the strings
l.indexOf("Last month")
times.map(_.getOrElse("") adds an additional walk of the list - certainly not necessary for what you're trying to do.List[Option[String]] to List[String] and find the index of the element with a certain value in one pass, then you can combine it in the map function. However, you basically double the operations of your map function, which will lead to the same complexity as with the two pass approach (assuming that you have only few cache misses).Perhaps not as efficient as indexOf, but more readable, I'd argue:
scala> times.zipWithIndex.find(
{ case (value, _) => value == Some("Last week") }
).map(_._2)
res7: Option[Int] = Some(0)
Or, using flatMap:
scala> times.zipWithIndex.flatMap {
| case (value, index) => value match {
| case Some("Last week") => ArrayBuffer(index)
| case _ => Nil
| }
| }
res2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0)