简体   繁体   English

如何在Scala中过滤Seq

[英]How to filter a Seq in 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 我有一个问题,我有一个Scala Seq of Fruit Objects,其中对象的名称成员变量是水果的名称,例如

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 我有一个scala字符串,其中包含以逗号分隔的水果的名称,例如

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, 我需要过滤上面的Seq,使其仅包含我喜欢的Fruit的对象,这就是结果,

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. 我尝试了Java方式,但是我对如何以Scala方式进行相同的工作很感兴趣。 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 : 如果ilike包含一个其子字符串位于fruit中的名称,则仅使用ilike.contains作为过滤器函数将失败:

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: 因此,应该先将ilike分为一系列偏好设置:

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

Now it's safe to use like.contains for filtering: 现在可以安全地使用like.contains进行过滤:

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 编辑:如果水果包含带有name成员的Fruit实例列表,则只需使用

scala> fruits.filter(f => like.contains(f.name)
res3: Seq[Fruit] = List(pineapple, grapes, watermelon)

An even more succinct way - use intersect 更加简洁的方法-使用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. 考虑到1.这可能是正确的答案吗?1.我喜欢的值可以为空。 If it is empty the return Seq should be fruits. 如果为空,则返回Seq应该是结果。 2. the val ilike can be seperated by a comma or a comma and space. 2.值可以用逗号或逗号和空格分隔。

if(ilike != "") {
  val like = for(i <- ilike.split(",")) yield i.trim
  fruits.filter(f => like.contains(f.name))
} else {
  fruits
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM