如何在 Scala 中结合过滤器和映射? [英] How to combine filter and map in 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屋!