且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在scala中组合过滤器和地图?

更新时间:2023-09-22 13:30:52

正如我在我的评论中所说,收集应该做你想要的:

As I state in my comment, collect should do what you want:

list.collect{
  case x if x % 2 == 0 => x*2
}

收集方法允许您同时指定匹配元素( filter )的条件,并修改匹配的值( map

The collect method allows you to both specify a criteria on the matching elements (filter) and modify the values that match (map)

而且,在@TravisBrown建议的情况下,您也可以使用 flatMap ,特别是在条件为更复杂,不适合作为防卫条件。这样的例子如下:

And as @TravisBrown suggested, you can use flatMap as well, especially in situations where the condition is more complex and not suitable as a guard condition. Something like this for your example:

list.flatMap{
  case x if x % 2 == 0 => Some(x*2)
  case x => None
}