如何在scala中组合过滤器和地图? [英] How to combine filter and map in scala?
问题描述
我在 Scala
中有列表[Int]
。列表是列表(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 muliply the numbers with 2. Is it possible?
我希望我能清楚地解释这个问题。如果你有任何问题,请问。
I hope I have explained the question clearly. If u have any questions then please ask. THanks in advance.
推荐答案
正如我在我的评论中所说,收集
应该做你想要的:
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
}
这篇关于如何在scala中组合过滤器和地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!