Iterate through odd members of collection in Scala
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)
scala> List("apples", "oranges", "pears", "bananas").drop(1).sliding(1, 2).flatten.toList
res0: List[java.lang.String] = List(oranges, bananas)