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.
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)
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