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.
Just using ilike.contains
as the filter function fails if ilike
contains a name whose substring is in fruit
:
scala> val ilike = "pineapple, grapes, watermelon, guava"
ilike: String = pineapple, grapes, watermelon, guava
scala> fruits.filter(ilike.contains)
res1: Seq[String] = List(apple, pineapple, grapes, watermelon)
Therefore, ilike
should first be split into a sequence of preferences:
scala> val like = ilike.split(", ")
like: Array[String] = Array(pineapple, grapes, watermelon, guava)
Now it's safe to use like.contains
for filtering:
scala> fruits.filter(like.contains)
res3: Seq[String] = List(pineapple, grapes, watermelon)
Edit: If fruits contains a list of Fruit
instances with a name
member, just use
scala> fruits.filter(f => like.contains(f.name)
res3: Seq[Fruit] = List(pineapple, grapes, watermelon)
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)
很简单:
fruits.filter(f=>ilike.split(",").contains(f.name))
Can this be the correct answer, considering 1. the val ilike can be empty. If it is empty the return Seq should be fruits. 2. the val ilike can be seperated by a comma or a comma and space.
if(ilike != "") {
val like = for(i <- ilike.split(",")) yield i.trim
fruits.filter(f => like.contains(f.name))
} else {
fruits
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.