I am trying to find a way to find consecutive elements in a collection in Scala based on a desired element being in the first position. I'd like to achieve this with functional programming, so I'm struggling on coming up with an approach.
Basically, I have a list foo
which can contain either A
, B
or C
. 'A' being the desired value, so it is necessary that 'A' is first, or else, the resulting bar
should be empty.
From the first element, I need to extract the consecutive elements up until there is a change in the element value, then create a new list bar
which contains the sequence of elements prior to the one that was different.
So for example, what I wanna do is
List('A', 'A', 'B', 'C', 'A', 'B') => List('A', 'A')
At the same time, if the first element is not A, then the resulting List should be empty
List('B', 'A', 'A', 'C') => List()
I have tried to apply foreach
on a List foo
and check if the current element is the desired element to add it to a list, but due to Scala immutability (I know you can use mutable but I'd rather not) I don't know how to keep track of the previous elements and output the collection
CodePudding user response:
If the first element always has to be A
, then takeWhile
does what you want.
scala> List('A', 'A', 'B', 'C', 'A', 'B').takeWhile(_ == 'A')
val res3: List[Char] = List(A, A)
CodePudding user response:
You can use takeWhile
:
list.headOption()
.map(el => list.takeWhile(_ == el))
.getOrElse(List())
If you want only 'A'
, then you can reduce the code to only the middle line, as in Brian's answer.