What is an efficient way to iterate through only the odd members of a collection in Scala, based on index position?
Given this list:
val fruits: List[String] = List("apples", "oranges", "pears", "bananas")
I want to to skip apples and pears, and process oranges and bananas. Thanks!
Update based on responses given:
Wow, each of the top three answers has merit. I originally meant the word "efficient" from a Scala Collections syntax perspective, and I was really just looking for a slick way to create the sublist for subsequent iteration. @Senia does a good job introducing the sliding() function, great for this particular use case, but I also like @Brian's more generalized approach using zipWithIndex().
However, when I consider the actual wording of the question as originally asked and the computational efficiency of @sourcedelica's response, I think he takes the prize for this one.
scala> List("apples", "oranges", "pears", "bananas").drop(1).sliding(1, 2).flatten.toList
res0: List[java.lang.String] = List(oranges, bananas)
val fruits: List[String] = List("apples", "oranges", "pears", "bananas")
fruits.zipWithIndex.filter(_._2 % 2 == 1).map(_._1)
res0: List[String] = List(oranges, bananas)
zipWithIndex pairs each element in List with an index giving:
List[(String, Int)] = List((apples,0), (oranges,1), (pears,2), (bananas,3))
filter the odd elements with filter(_._2 % 2 == 1)
giving:
List[(String, Int)] = List((oranges,1), (bananas,3))
map the List[(String, Int)] to just List[String] by taking the first element of each tuple with .map(_._1)
giving:
List[String] = List(oranges, bananas)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With