scala 两个条件下的Scala过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11127594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 04:16:06  来源:igfitidea点击:

Scala filter on two conditions

arraysscalafiltermultiple-conditions

提问by richsoni

I would like to filter my data set on two conditions at once.

我想一次在两个条件下过滤我的数据集。

Is it possible?

是否可以?

I want something like this:

我想要这样的东西:

mystuff = mystuff.filter(_.isX && _.name == "xyz")

回答by Alex Wilson

Using slightly less concise lambda syntax:

使用稍微不那么简洁的 lambda 语法:

mystuff = mystuff.filter(x => (x.isX && x.name == "xyz"))

You can find more detail on Scala anonymous function syntax here.

您可以在此处找到有关 Scala 匿名函数语法的更多详细信息。

回答by Dave Griffith

While there might be some performance impact depending on what "myStuff" is, you could always filter twice

虽然根据“myStuff”的含义可能会对性能产生一些影响,但您始终可以过滤两次

mystuff = mystuff.filter(_.isX).filter(_.name == "xyz")

回答by paradigmatic

If you need to frequently filter with several predicate, you could define a way of combining them:

如果您需要经常使用多个谓词进行过滤,您可以定义一种组合方式:

case class And[A]( p1: A=>Boolean, p2: A=>Boolean ) extends (A=>Boolean) {
  def apply( a: A ) = p1(a) && p2(a)
}

Here is how to use it to keep only the odd numbers bigger than 10:

以下是如何使用它来仅保留大于 10 的奇数:

scala> (0 until 20) filter And( _ > 10, _ % 2 == 1 )
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(11, 13, 15, 17, 19)

It easy to write Orand Notcombinators in the same fashion.

以相同的方式编写OrNot组合器很容易。