Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to find consecutive elements in a collection in Scala

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading