1

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?

3 Answers 3

4

You can use indexOf

times.indexOf(Some("Last month")) // returns 1

Update

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")
Sign up to request clarification or add additional context in comments.

3 Comments

How to convert in list (Remove Some )for eg: List("Last week", "Last month". "Last year")
Understood that you answered his question, Till. But, calling times.map(_.getOrElse("") adds an additional walk of the list - certainly not necessary for what you're trying to do.
You're right @KevinMeredith. This is not the most efficient solution. If you want to convert the list from 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).
2

You can use indexOf or lastIndexOf. Example:

 times indexOf ( Some( "Last year" ) ) 

Also you can use indexWhere or lastIndexWhere. For example:

times indexWhere { _.get == "Last year" }

Comments

1

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)

1 Comment

I could not use the indexOf approach. I used this approach as my object in the ArrayBuffer was not simple String - but a complex one. I used one of the attributes to find the object and zipWithIndex helped getting the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.