如何在 Scala 中结合过滤器和映射? [英] How to combine filter and map in Scala?

查看:21
本文介绍了如何在 Scala 中结合过滤器和映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Scala 中有 List[Int].列表是 List(1,2,3,4,5,6,7,8,9,10).我想 filter 列表,以便它只有偶数.我想将数字乘以 2.

I have List[Int] in Scala. The List is List(1,2,3,4,5,6,7,8,9,10). I want to filter the list so that it only has even numbers. And I want to multiply the numbers with 2.

有可能吗?

推荐答案

正如我在评论中所说,collect 应该做你想做的事:

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

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

collect 方法允许您指定匹配元素的条件 (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
}

这篇关于如何在 Scala 中结合过滤器和映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆