Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a Seq in Scala

Tags:

scala

I have a question, I have a Scala Seq of Fruit Objects, where the name member variable of the object is the name of the fruit like

fruits: Seq[Fruit] = List(banana, apple, jackfruit, pineapple, grapes, watermelon, papaya, orange, pomegranate, strawberry)

and I have a scala String which contains the name of the fruit separated by comma like

val ilike = "apple, grapes, watermelon, guava"

I need to filter the above Seq such that it contain only the objects of Fruit I like, that is the result should be,

fruits: Seq[Fruit] = List(apple, grapes, watermelon)

I tried the Java way, but I am interested how to work the same in the Scala way. I googled a bit but I couldn't find the correct answer.

Thank You for your help in advance.

like image 736
vj2015 Avatar asked Jan 20 '26 15:01

vj2015


1 Answers

An even more succinct way - use intersect

scala> val like = ilike.split(", ")
like: Array[String] = Array(pineapple, grapes, watermelon, guava)

scala> fruits.intersect(like)
res1: Seq[String] = List(pineapple, grapes, watermelon)
like image 116
Callum Avatar answered Jan 23 '26 20:01

Callum



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!