scala 地图功能中的条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29426250/
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 07:02:52  来源:igfitidea点击:

Condition in map function

scalaapache-sparkspark-streamingmap-function

提问by Lisa

Is there anything in Scala like,

Scala 中有什么类似的东西,

condition ? first_expression : second_expression;

that I can use within map function in scala? I want to be able to write something like this:

我可以在 Scala 的 map 函数中使用吗?我希望能够写出这样的东西:

val statuses = tweets.map(status => status.isTruncate? //do nothing | status.getText())

If the inline function is not possible, how can I write a condition within map?

如果无法使用内联函数,我如何在其中写入条件map

回答by Ben Reich

The ?operator, sometimes called the ternary operatoris not necessary in Scala, since it is subsumed by a regular if-elseexpression:

?操作者,有时也被称为三元运算符是不Scala中必要的,因为它是由有规律归入if-else表达式:

val x = if (condition) 1 else 2

To use this in a map, you can use flatMapand then return an Optionon either side of the if-else. Since Optionis implicitly convertible to Iterable, the effect is that the list is flattened, and the Nonesare filtered:

要在 a 中使用它map,您可以在 的任一侧使用flatMap然后返回 an 。由于可隐式转换为,效果是列表被展平,并且被过滤:Optionif-elseOptionIterableNones

val statuses = tweets.flatMap(status => if (status.isTruncate) None else Some(status.getText))

This is equivalent to using mapand then flatten:

这相当于使用map然后flatten

val statuses = tweets.map(status => if (status.isTruncate) None else Some(status.getText)).flatten

More idiomatically, you can use collect, which allows you to filterand mapin one step using a partial function:

更惯用,可以使用collect,它允许你filtermap在一个步骤中使用的局部功能:

val statuses = tweets.collect {
    case status if !status.isTruncate => status.getText
}

You can also do this in 2 steps using filterand map:

您也可以使用filterand分两步执行此操作map

val statuses = tweets.filterNot(_.isTruncate).map(_.getText)

The downside here is that this will iterate over the list twice, which may be undesirable. If you use view, you can use this same logic and only iterate over the list once:

这里的缺点是这将遍历列表两次,这可能是不可取的。如果使用view,则可以使用相同的逻辑,并且只对列表进行一次迭代:

val statuses = tweets.view.filterNot(_.isTruncate).map(_.getText)

回答by S.Karthik

you can filter and then map like,

你可以过滤然后映射,

  val statuses = tweets.filter(_.isTruncate).map(status=> status.getText())